at commit a0189536

1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "builtin.h"
4 #include "abspath.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hash.h"
9 #include "hex.h"
10 #include "object-name.h"
11 #include "parse-options.h"
12 #include "refs.h"
13 #include "stash.h"
14 #include "lockfile.h"
15 #include "cache-tree.h"
16 #include "unpack-trees.h"
17 #include "merge-ort-wrappers.h"
18 #include "strvec.h"
19 #include "run-command.h"
20 #include "dir.h"
21 #include "entry.h"
22 #include "preload-index.h"
23 #include "read-cache.h"
24 #include "repository.h"
25 #include "rerere.h"
26 #include "revision.h"
27 #include "setup.h"
28 #include "sparse-index.h"
29 #include "log-tree.h"
30 #include "diffcore.h"
31 #include "reflog.h"
32 #include "reflog-walk.h"
33 #include "add-interactive.h"
34 #include "oid-array.h"
35 #include "commit.h"
36
37 #define INCLUDE_ALL_FILES 2
38
39 #define BUILTIN_STASH_LIST_USAGE \
40 N_("git stash list [<log-options>]")
41 #define BUILTIN_STASH_SHOW_USAGE \
42 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
43 #define BUILTIN_STASH_DROP_USAGE \
44 N_("git stash drop [-q | --quiet] [<stash>]")
45 #define BUILTIN_STASH_POP_USAGE \
46 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
47 #define BUILTIN_STASH_APPLY_USAGE \
48 N_("git stash apply [--index] [-q | --quiet] [--label-ours=<label>] [--label-theirs=<label>] [--label-base=<label>] [<stash>]")
49 #define BUILTIN_STASH_BRANCH_USAGE \
50 N_("git stash branch <branchname> [<stash>]")
51 #define BUILTIN_STASH_STORE_USAGE \
52 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
53 #define BUILTIN_STASH_PUSH_USAGE \
54 N_("git stash [push] [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
55 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
56 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
57 " [--] [<pathspec>...]")
58 #define BUILTIN_STASH_SAVE_USAGE \
59 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
60 " [-u | --include-untracked] [-a | --all] [<message>]")
61 #define BUILTIN_STASH_CREATE_USAGE \
62 N_("git stash create [<message>]")
63 #define BUILTIN_STASH_EXPORT_USAGE \
64 N_("git stash export (--print | --to-ref <ref>) [<stash>...]")
65 #define BUILTIN_STASH_IMPORT_USAGE \
66 N_("git stash import <commit>")
67 #define BUILTIN_STASH_CLEAR_USAGE \
68 "git stash clear"
69
70 static const char * const git_stash_usage[] = {
71 BUILTIN_STASH_LIST_USAGE,
72 BUILTIN_STASH_SHOW_USAGE,
73 BUILTIN_STASH_DROP_USAGE,
74 BUILTIN_STASH_POP_USAGE,
75 BUILTIN_STASH_APPLY_USAGE,
76 BUILTIN_STASH_BRANCH_USAGE,
77 BUILTIN_STASH_PUSH_USAGE,
78 BUILTIN_STASH_SAVE_USAGE,
79 BUILTIN_STASH_CLEAR_USAGE,
80 BUILTIN_STASH_CREATE_USAGE,
81 BUILTIN_STASH_STORE_USAGE,
82 BUILTIN_STASH_EXPORT_USAGE,
83 BUILTIN_STASH_IMPORT_USAGE,
84 NULL
85 };
86
87 static const char * const git_stash_list_usage[] = {
88 BUILTIN_STASH_LIST_USAGE,
89 NULL
90 };
91
92 static const char * const git_stash_show_usage[] = {
93 BUILTIN_STASH_SHOW_USAGE,
94 NULL
95 };
96
97 static const char * const git_stash_drop_usage[] = {
98 BUILTIN_STASH_DROP_USAGE,
99 NULL
100 };
101
102 static const char * const git_stash_pop_usage[] = {
103 BUILTIN_STASH_POP_USAGE,
104 NULL
105 };
106
107 static const char * const git_stash_apply_usage[] = {
108 BUILTIN_STASH_APPLY_USAGE,
109 NULL
110 };
111
112 static const char * const git_stash_branch_usage[] = {
113 BUILTIN_STASH_BRANCH_USAGE,
114 NULL
115 };
116
117 static const char * const git_stash_clear_usage[] = {
118 BUILTIN_STASH_CLEAR_USAGE,
119 NULL
120 };
121
122 static const char * const git_stash_store_usage[] = {
123 BUILTIN_STASH_STORE_USAGE,
124 NULL
125 };
126
127 static const char * const git_stash_push_usage[] = {
128 BUILTIN_STASH_PUSH_USAGE,
129 NULL
130 };
131
132 static const char * const git_stash_save_usage[] = {
133 BUILTIN_STASH_SAVE_USAGE,
134 NULL
135 };
136
137 static const char * const git_stash_export_usage[] = {
138 BUILTIN_STASH_EXPORT_USAGE,
139 NULL
140 };
141
142 static const char * const git_stash_import_usage[] = {
143 BUILTIN_STASH_IMPORT_USAGE,
144 NULL
145 };
146
147 static const char ref_stash[] = "refs/stash";
148 static struct strbuf stash_index_path = STRBUF_INIT;
149
150 static int show_stat = 1;
151 static int show_patch;
152 static int show_include_untracked;
153 static int use_index;
154
155 /*
156 * w_commit is set to the commit containing the working tree
157 * b_commit is set to the base commit
158 * i_commit is set to the commit containing the index tree
159 * u_commit is set to the commit containing the untracked files tree
160 * c_commit is set to the first parent (chain commit) when importing and is otherwise unset
161 * w_tree is set to the working tree
162 * b_tree is set to the base tree
163 * i_tree is set to the index tree
164 * u_tree is set to the untracked files tree
165 */
166 struct stash_info {
167 struct object_id w_commit;
168 struct object_id b_commit;
169 struct object_id i_commit;
170 struct object_id u_commit;
171 struct object_id c_commit;
172 struct object_id w_tree;
173 struct object_id b_tree;
174 struct object_id i_tree;
175 struct object_id u_tree;
176 struct strbuf revision;
177 int is_stash_ref;
178 int has_u;
179 };
180
181 #define STASH_INFO_INIT { \
182 .revision = STRBUF_INIT, \
183 }
184
185 static void free_stash_info(struct stash_info *info)
186 {
187 strbuf_release(&info->revision);
188 }
189
190 static int check_stash_topology(struct repository *r, struct commit *stash)
191 {
192 struct commit *p1, *p2, *p3 = NULL;
193
194 /* stash must have two or three parents */
195 if (!stash->parents || !stash->parents->next ||
196 (stash->parents->next->next && stash->parents->next->next->next))
197 return -1;
198 p1 = stash->parents->item;
199 p2 = stash->parents->next->item;
200 if (stash->parents->next->next)
201 p3 = stash->parents->next->next->item;
202 if (repo_parse_commit(r, p1) || repo_parse_commit(r, p2) ||
203 (p3 && repo_parse_commit(r, p3)))
204 return -1;
205 /* p2 must have a single parent, p3 must have no parents */
206 if (!p2->parents || p2->parents->next || (p3 && p3->parents))
207 return -1;
208 if (repo_parse_commit(r, p2->parents->item))
209 return -1;
210 /* p2^1 must equal p1 */
211 if (!oideq(&p1->object.oid, &p2->parents->item->object.oid))
212 return -1;
213
214 return 0;
215 }
216
217 static void assert_stash_like(struct stash_info *info, const char *revision)
218 {
219 if (get_oidf(&info->b_commit, "%s^1", revision) ||
220 get_oidf(&info->w_tree, "%s:", revision) ||
221 get_oidf(&info->b_tree, "%s^1:", revision) ||
222 get_oidf(&info->i_tree, "%s^2:", revision))
223 die(_("'%s' is not a stash-like commit"), revision);
224 }
225
226 static int parse_stash_revision(struct strbuf *revision, const char *commit, int quiet)
227 {
228 strbuf_reset(revision);
229 if (!commit) {
230 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash)) {
231 if (!quiet)
232 fprintf_ln(stderr, _("No stash entries found."));
233 return -1;
234 }
235
236 strbuf_addf(revision, "%s@{0}", ref_stash);
237 } else if (strspn(commit, "0123456789") == strlen(commit)) {
238 strbuf_addf(revision, "%s@{%s}", ref_stash, commit);
239 } else {
240 strbuf_addstr(revision, commit);
241 }
242 return 0;
243 }
244
245 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
246 {
247 int ret;
248 char *end_of_rev;
249 char *expanded_ref;
250 const char *revision;
251 const char *commit = NULL;
252 struct object_id dummy;
253 struct strbuf symbolic = STRBUF_INIT;
254
255 if (argc > 1) {
256 int i;
257 struct strbuf refs_msg = STRBUF_INIT;
258
259 for (i = 0; i < argc; i++)
260 strbuf_addf(&refs_msg, " '%s'", argv[i]);
261
262 fprintf_ln(stderr, _("Too many revisions specified:%s"),
263 refs_msg.buf);
264 strbuf_release(&refs_msg);
265
266 return -1;
267 }
268
269 if (argc == 1)
270 commit = argv[0];
271
272 strbuf_init(&info->revision, 0);
273 if (parse_stash_revision(&info->revision, commit, 0)) {
274 return -1;
275 }
276
277 revision = info->revision.buf;
278
279 if (repo_get_oid(the_repository, revision, &info->w_commit))
280 return error(_("%s is not a valid reference"), revision);
281
282 assert_stash_like(info, revision);
283
284 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
285
286 end_of_rev = strchrnul(revision, '@');
287 strbuf_add(&symbolic, revision, end_of_rev - revision);
288
289 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
290 &dummy, &expanded_ref, 0);
291 strbuf_release(&symbolic);
292 switch (ret) {
293 case 0: /* Not found, but valid ref */
294 info->is_stash_ref = 0;
295 break;
296 case 1:
297 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
298 break;
299 default: /* Invalid or ambiguous */
300 break;
301 }
302
303 free(expanded_ref);
304 return !(ret == 0 || ret == 1);
305 }
306
307 static int do_clear_stash(void)
308 {
309 struct object_id obj;
310 if (repo_get_oid(the_repository, ref_stash, &obj))
311 return 0;
312
313 return refs_delete_ref(get_main_ref_store(the_repository), NULL,
314 ref_stash, &obj, 0);
315 }
316
317 static int clear_stash(int argc, const char **argv, const char *prefix,
318 struct repository *repo UNUSED)
319 {
320 struct option options[] = {
321 OPT_END()
322 };
323
324 argc = parse_options(argc, argv, prefix, options,
325 git_stash_clear_usage,
326 PARSE_OPT_STOP_AT_NON_OPTION);
327
328 if (argc)
329 return error(_("git stash clear with arguments is "
330 "unimplemented"));
331
332 return do_clear_stash();
333 }
334
335 static int reset_tree(struct object_id *i_tree, int update, int reset)
336 {
337 int nr_trees = 1;
338 struct unpack_trees_options opts;
339 struct tree_desc t[MAX_UNPACK_TREES];
340 struct tree *tree;
341 struct lock_file lock_file = LOCK_INIT;
342
343 repo_read_index_preload(the_repository, NULL, 0);
344 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
345 return -1;
346
347 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
348
349 memset(&opts, 0, sizeof(opts));
350
351 tree = repo_parse_tree_indirect(the_repository, i_tree);
352 if (repo_parse_tree(the_repository, tree))
353 return -1;
354
355 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
356
357 opts.head_idx = 1;
358 opts.src_index = the_repository->index;
359 opts.dst_index = the_repository->index;
360 opts.merge = 1;
361 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
362 opts.update = update;
363 if (update)
364 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
365 opts.fn = oneway_merge;
366
367 if (unpack_trees(nr_trees, t, &opts))
368 return -1;
369
370 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
371 return error(_("unable to write new index file"));
372
373 return 0;
374 }
375
376 static int create_index_from_tree(const struct object_id *tree_id,
377 const char *index_path)
378 {
379 int nr_trees = 1;
380 int ret = 0;
381 struct unpack_trees_options opts;
382 struct tree_desc t[MAX_UNPACK_TREES];
383 struct tree *tree;
384 struct index_state dst_istate = INDEX_STATE_INIT(the_repository);
385 struct lock_file lock_file = LOCK_INIT;
386
387 repo_read_index_preload(the_repository, NULL, 0);
388 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
389
390 hold_lock_file_for_update(&lock_file, index_path, LOCK_DIE_ON_ERROR);
391
392 memset(&opts, 0, sizeof(opts));
393
394 tree = repo_parse_tree_indirect(the_repository, tree_id);
395 if (!tree || repo_parse_tree(the_repository, tree)) {
396 ret = -1;
397 goto done;
398 }
399
400 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
401
402 opts.head_idx = 1;
403 opts.src_index = the_repository->index;
404 opts.dst_index = &dst_istate;
405 opts.merge = 1;
406 opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
407 opts.fn = oneway_merge;
408
409 if (unpack_trees(nr_trees, t, &opts)) {
410 ret = -1;
411 goto done;
412 }
413
414 if (write_locked_index(&dst_istate, &lock_file, COMMIT_LOCK)) {
415 ret = error(_("unable to write new index file"));
416 goto done;
417 }
418
419 done:
420 release_index(&dst_istate);
421 if (ret)
422 rollback_lock_file(&lock_file);
423 return ret;
424 }
425
426 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
427 {
428 struct child_process cp = CHILD_PROCESS_INIT;
429 const char *w_commit_hex = oid_to_hex(w_commit);
430
431 /*
432 * Diff-tree would not be very hard to replace with a native function,
433 * however it should be done together with apply_cached.
434 */
435 cp.git_cmd = 1;
436 strvec_pushl(&cp.args, "diff-tree", "--binary", "--no-color", NULL);
437 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
438
439 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
440 }
441
442 static int apply_cached(struct strbuf *out)
443 {
444 struct child_process cp = CHILD_PROCESS_INIT;
445
446 /*
447 * Apply currently only reads either from stdin or a file, thus
448 * apply_all_patches would have to be updated to optionally take a
449 * buffer.
450 */
451 cp.git_cmd = 1;
452 strvec_pushl(&cp.args, "apply", "--cached", NULL);
453 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
454 }
455
456 static int reset_head(void)
457 {
458 struct child_process cp = CHILD_PROCESS_INIT;
459
460 /*
461 * Reset is overall quite simple, however there is no current public
462 * API for resetting.
463 */
464 cp.git_cmd = 1;
465 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
466
467 return run_command(&cp);
468 }
469
470 static int is_path_a_directory(const char *path)
471 {
472 /*
473 * This function differs from abspath.c:is_directory() in that
474 * here we use lstat() instead of stat(); we do not want to
475 * follow symbolic links here.
476 */
477 struct stat st;
478 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
479 }
480
481 static void add_diff_to_buf(struct diff_queue_struct *q,
482 struct diff_options *options UNUSED,
483 void *data)
484 {
485 int i;
486
487 for (i = 0; i < q->nr; i++) {
488 if (is_path_a_directory(q->queue[i]->one->path))
489 continue;
490
491 strbuf_addstr(data, q->queue[i]->one->path);
492
493 /* NUL-terminate: will be fed to update-index -z */
494 strbuf_addch(data, '\0');
495 }
496 }
497
498 static int restore_untracked(struct object_id *u_tree)
499 {
500 int res;
501 struct child_process cp = CHILD_PROCESS_INIT;
502
503 /*
504 * We need to run restore files from a given index, but without
505 * affecting the current index, so we use GIT_INDEX_FILE with
506 * run_command to fork processes that will not interfere.
507 */
508 cp.git_cmd = 1;
509 strvec_push(&cp.args, "read-tree");
510 strvec_push(&cp.args, oid_to_hex(u_tree));
511 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
512 stash_index_path.buf);
513 if (run_command(&cp)) {
514 remove_path(stash_index_path.buf);
515 return -1;
516 }
517
518 child_process_init(&cp);
519 cp.git_cmd = 1;
520 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
521 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
522 stash_index_path.buf);
523
524 res = run_command(&cp);
525 remove_path(stash_index_path.buf);
526 return res;
527 }
528
529 static void unstage_changes_unless_new(struct object_id *orig_tree)
530 {
531 /*
532 * When we enter this function, there has been a clean merge of
533 * relevant trees, and the merge logic always stages whatever merges
534 * cleanly. We want to unstage those changes, unless it corresponds
535 * to a file that didn't exist as of orig_tree.
536 *
537 * However, if any SKIP_WORKTREE path is modified relative to
538 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
539 * it to the worktree before unstaging.
540 */
541
542 struct checkout state = CHECKOUT_INIT;
543 struct diff_options diff_opts;
544 struct lock_file lock = LOCK_INIT;
545 int i;
546
547 /* If any entries have skip_worktree set, we'll have to check 'em out */
548 state.force = 1;
549 state.quiet = 1;
550 state.refresh_cache = 1;
551 state.istate = the_repository->index;
552
553 /*
554 * Step 1: get a difference between orig_tree (which corresponding
555 * to the index before a merge was run) and the current index
556 * (reflecting the changes brought in by the merge).
557 */
558 repo_diff_setup(the_repository, &diff_opts);
559 diff_opts.flags.recursive = 1;
560 diff_opts.detect_rename = 0;
561 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
562 diff_setup_done(&diff_opts);
563
564 do_diff_cache(orig_tree, &diff_opts);
565 diffcore_std(&diff_opts);
566
567 /* Iterate over the paths that changed due to the merge... */
568 for (i = 0; i < diff_queued_diff.nr; i++) {
569 struct diff_filepair *p;
570 struct cache_entry *ce;
571 int pos;
572
573 /* Look up the path's position in the current index. */
574 p = diff_queued_diff.queue[i];
575 pos = index_name_pos(the_repository->index, p->two->path,
576 strlen(p->two->path));
577
578 /*
579 * Step 2: Place changes in the working tree
580 *
581 * Stash is about restoring changes *to the working tree*.
582 * So if the merge successfully got a new version of some
583 * path, but left it out of the working tree, then clear the
584 * SKIP_WORKTREE bit and write it to the working tree.
585 */
586 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
587 struct stat st;
588
589 ce = the_repository->index->cache[pos];
590 if (!lstat(ce->name, &st)) {
591 /* Conflicting path present; relocate it */
592 struct strbuf new_path = STRBUF_INIT;
593 int fd;
594
595 strbuf_addf(&new_path,
596 "%s.stash.XXXXXX", ce->name);
597 fd = xmkstemp(new_path.buf);
598 close(fd);
599 printf(_("WARNING: Untracked file in way of "
600 "tracked file! Renaming\n "
601 " %s -> %s\n"
602 " to make room.\n"),
603 ce->name, new_path.buf);
604 if (rename(ce->name, new_path.buf))
605 die("Failed to move %s to %s",
606 ce->name, new_path.buf);
607 strbuf_release(&new_path);
608 }
609 checkout_entry(ce, &state, NULL, NULL);
610 ce->ce_flags &= ~CE_SKIP_WORKTREE;
611 }
612
613 /*
614 * Step 3: "unstage" changes, as long as they are still tracked
615 */
616 if (p->one->oid_valid) {
617 /*
618 * Path existed in orig_tree; restore index entry
619 * from that tree in order to "unstage" the changes.
620 */
621 int option = ADD_CACHE_OK_TO_REPLACE;
622 if (pos < 0)
623 option = ADD_CACHE_OK_TO_ADD;
624
625 ce = make_cache_entry(the_repository->index,
626 p->one->mode,
627 &p->one->oid,
628 p->one->path,
629 0, 0);
630 add_index_entry(the_repository->index, ce, option);
631 }
632 }
633 diff_flush(&diff_opts);
634
635 /*
636 * Step 4: write the new index to disk
637 */
638 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
639 if (write_locked_index(the_repository->index, &lock,
640 COMMIT_LOCK | SKIP_IF_UNCHANGED))
641 die(_("could not write index"));
642 }
643
644 static enum stash_apply_result do_apply_stash(const char *prefix,
645 struct stash_info *info,
646 int index, int quiet,
647 const char *label_ours,
648 const char *label_theirs,
649 const char *label_base)
650 {
651 int clean, ret;
652 int has_index = index;
653 struct merge_options o;
654 struct object_id c_tree;
655 struct object_id index_tree;
656 struct tree *head, *merge, *merge_base;
657 struct lock_file lock = LOCK_INIT;
658
659 repo_read_index_preload(the_repository, NULL, 0);
660 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
661 NULL, NULL, NULL))
662 return error(_("could not write index"));
663
664 if (write_index_as_tree(&c_tree, the_repository->index,
665 repo_get_index_file(the_repository), 0, NULL))
666 return error(_("cannot apply a stash in the middle of a merge"));
667
668 if (index) {
669 if (oideq(&info->b_tree, &info->i_tree) ||
670 oideq(&c_tree, &info->i_tree)) {
671 has_index = 0;
672 } else {
673 struct strbuf out = STRBUF_INIT;
674
675 if (diff_tree_binary(&out, &info->w_commit)) {
676 strbuf_release(&out);
677 return error(_("could not generate diff %s^!."),
678 oid_to_hex(&info->w_commit));
679 }
680
681 ret = apply_cached(&out);
682 strbuf_release(&out);
683 if (ret)
684 return error(_("conflicts in index. "
685 "Try without --index."));
686
687 discard_index(the_repository->index);
688 repo_read_index(the_repository);
689 if (write_index_as_tree(&index_tree, the_repository->index,
690 repo_get_index_file(the_repository), 0, NULL))
691 return error(_("could not save index tree"));
692
693 reset_head();
694 discard_index(the_repository->index);
695 repo_read_index(the_repository);
696 }
697 }
698
699 init_ui_merge_options(&o, the_repository);
700
701 o.branch1 = label_ours ? label_ours : "Updated upstream";
702 o.branch2 = label_theirs ? label_theirs : "Stashed changes";
703 o.ancestor = label_base ? label_base : "Stash base";
704
705 if (oideq(&info->b_tree, &c_tree))
706 o.branch1 = "Version stash was based on";
707
708 if (quiet)
709 o.verbosity = 0;
710
711 if (o.verbosity >= 3)
712 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
713
714 head = lookup_tree(o.repo, &c_tree);
715 merge = lookup_tree(o.repo, &info->w_tree);
716 merge_base = lookup_tree(o.repo, &info->b_tree);
717
718 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
719 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
720
721 /*
722 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
723 * merge was clean, and 1 if the merge was unclean or a negative value
724 * if it encountered an error.
725 */
726 ret = clean >= 0 ? !clean : clean;
727
728 if (ret < 0)
729 rollback_lock_file(&lock);
730 else if (write_locked_index(o.repo->index, &lock,
731 COMMIT_LOCK | SKIP_IF_UNCHANGED))
732 ret = error(_("could not write index"));
733
734 if (ret) {
735 repo_rerere(the_repository, 0);
736
737 if (index)
738 fprintf_ln(stderr, _("Index was not unstashed."));
739
740 goto restore_untracked;
741 }
742
743 if (has_index) {
744 if (reset_tree(&index_tree, 0, 0))
745 ret = -1;
746 } else {
747 unstage_changes_unless_new(&c_tree);
748 }
749
750 restore_untracked:
751 if (info->has_u && restore_untracked(&info->u_tree))
752 ret = error(_("could not restore untracked files from stash"));
753
754 if (!quiet) {
755 struct child_process cp = CHILD_PROCESS_INIT;
756
757 /*
758 * Status is quite simple and could be replaced with calls to
759 * wt_status in the future, but it adds complexities which may
760 * require more tests.
761 */
762 cp.git_cmd = 1;
763 cp.dir = prefix;
764 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
765 absolute_path(repo_get_work_tree(the_repository)));
766 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
767 absolute_path(repo_get_git_dir(the_repository)));
768 strvec_push(&cp.args, "status");
769 run_command(&cp);
770 }
771
772 return ret;
773 }
774
775 static int apply_stash(int argc, const char **argv, const char *prefix,
776 struct repository *repo UNUSED)
777 {
778 int ret = -1;
779 int quiet = 0;
780 int index = use_index;
781 const char *label_ours = NULL, *label_theirs = NULL, *label_base = NULL;
782 struct stash_info info = STASH_INFO_INIT;
783 struct option options[] = {
784 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
785 OPT_BOOL(0, "index", &index,
786 N_("attempt to recreate the index")),
787 OPT_STRING(0, "label-ours", &label_ours, N_("label"),
788 N_("label for the upstream side in conflict markers")),
789 OPT_STRING(0, "label-theirs", &label_theirs, N_("label"),
790 N_("label for the stashed side in conflict markers")),
791 OPT_STRING(0, "label-base", &label_base, N_("label"),
792 N_("label for the base in diff3 conflict markers")),
793 OPT_END()
794 };
795
796 argc = parse_options(argc, argv, prefix, options,
797 git_stash_apply_usage, 0);
798
799 if (get_stash_info(&info, argc, argv))
800 goto cleanup;
801
802 ret = do_apply_stash(prefix, &info, index, quiet,
803 label_ours, label_theirs, label_base);
804 cleanup:
805 free_stash_info(&info);
806 return ret;
807 }
808
809 static int reject_reflog_ent(const char *refname UNUSED,
810 struct object_id *ooid UNUSED,
811 struct object_id *noid UNUSED,
812 const char *email UNUSED,
813 timestamp_t timestamp UNUSED,
814 int tz UNUSED, const char *message UNUSED,
815 void *cb_data UNUSED)
816 {
817 return 1;
818 }
819
820 static int reflog_is_empty(const char *refname)
821 {
822 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository),
823 refname, reject_reflog_ent, NULL);
824 }
825
826 static int do_drop_stash(struct stash_info *info, int quiet)
827 {
828 if (!reflog_delete(info->revision.buf,
829 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
830 0)) {
831 if (!quiet)
832 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
833 oid_to_hex(&info->w_commit));
834 } else {
835 return error(_("%s: Could not drop stash entry"),
836 info->revision.buf);
837 }
838
839 if (reflog_is_empty(ref_stash))
840 do_clear_stash();
841
842 return 0;
843 }
844
845 static int get_stash_info_assert(struct stash_info *info, int argc,
846 const char **argv)
847 {
848 int ret = get_stash_info(info, argc, argv);
849
850 if (ret < 0)
851 return ret;
852
853 if (!info->is_stash_ref)
854 return error(_("'%s' is not a stash reference"), info->revision.buf);
855
856 return 0;
857 }
858
859 static int drop_stash(int argc, const char **argv, const char *prefix,
860 struct repository *repo UNUSED)
861 {
862 int ret = -1;
863 int quiet = 0;
864 struct stash_info info = STASH_INFO_INIT;
865 struct option options[] = {
866 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
867 OPT_END()
868 };
869
870 argc = parse_options(argc, argv, prefix, options,
871 git_stash_drop_usage, 0);
872
873 if (get_stash_info_assert(&info, argc, argv))
874 goto cleanup;
875
876 ret = do_drop_stash(&info, quiet);
877 cleanup:
878 free_stash_info(&info);
879 return ret;
880 }
881
882 static int pop_stash(int argc, const char **argv, const char *prefix,
883 struct repository *repo UNUSED)
884 {
885 int ret = -1;
886 int index = use_index;
887 int quiet = 0;
888 struct stash_info info = STASH_INFO_INIT;
889 struct option options[] = {
890 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
891 OPT_BOOL(0, "index", &index,
892 N_("attempt to recreate the index")),
893 OPT_END()
894 };
895
896 argc = parse_options(argc, argv, prefix, options,
897 git_stash_pop_usage, 0);
898
899 if (get_stash_info_assert(&info, argc, argv))
900 goto cleanup;
901
902 if ((ret = do_apply_stash(prefix, &info, index, quiet,
903 NULL, NULL, NULL)))
904 printf_ln(_("The stash entry is kept in case "
905 "you need it again."));
906 else
907 ret = do_drop_stash(&info, quiet);
908
909 cleanup:
910 free_stash_info(&info);
911 return ret;
912 }
913
914 static int branch_stash(int argc, const char **argv, const char *prefix,
915 struct repository *repo UNUSED)
916 {
917 int ret = -1;
918 const char *branch = NULL;
919 struct stash_info info = STASH_INFO_INIT;
920 struct child_process cp = CHILD_PROCESS_INIT;
921 struct option options[] = {
922 OPT_END()
923 };
924
925 argc = parse_options(argc, argv, prefix, options,
926 git_stash_branch_usage, 0);
927
928 if (!argc) {
929 fprintf_ln(stderr, _("No branch name specified"));
930 return -1;
931 }
932
933 branch = argv[0];
934
935 if (get_stash_info(&info, argc - 1, argv + 1))
936 goto cleanup;
937
938 cp.git_cmd = 1;
939 strvec_pushl(&cp.args, "checkout", "-b", NULL);
940 strvec_push(&cp.args, branch);
941 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
942 ret = run_command(&cp);
943 if (!ret)
944 ret = do_apply_stash(prefix, &info, 1, 0,
945 NULL, NULL, NULL);
946 if (!ret && info.is_stash_ref)
947 ret = do_drop_stash(&info, 0);
948
949 cleanup:
950 free_stash_info(&info);
951 return ret;
952 }
953
954 static int list_stash(int argc, const char **argv, const char *prefix,
955 struct repository *repo UNUSED)
956 {
957 struct child_process cp = CHILD_PROCESS_INIT;
958 struct option options[] = {
959 OPT_END()
960 };
961
962 argc = parse_options(argc, argv, prefix, options,
963 git_stash_list_usage,
964 PARSE_OPT_KEEP_UNKNOWN_OPT);
965
966 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash))
967 return 0;
968
969 cp.git_cmd = 1;
970 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
971 "--first-parent", NULL);
972 strvec_pushv(&cp.args, argv);
973 strvec_push(&cp.args, ref_stash);
974 strvec_push(&cp.args, "--");
975 return run_command(&cp);
976 }
977
978 static int git_stash_config(const char *var, const char *value,
979 const struct config_context *ctx, void *cb)
980 {
981 if (!strcmp(var, "stash.showstat")) {
982 show_stat = git_config_bool(var, value);
983 return 0;
984 }
985 if (!strcmp(var, "stash.showpatch")) {
986 show_patch = git_config_bool(var, value);
987 return 0;
988 }
989 if (!strcmp(var, "stash.showincludeuntracked")) {
990 show_include_untracked = git_config_bool(var, value);
991 return 0;
992 }
993 if (!strcmp(var, "stash.index")) {
994 use_index = git_config_bool(var, value);
995 return 0;
996 }
997 return git_diff_basic_config(var, value, ctx, cb);
998 }
999
1000 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
1001 {
1002 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
1003 struct tree *tree[ARRAY_SIZE(oid)];
1004 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
1005 struct unpack_trees_options unpack_tree_opt = { 0 };
1006
1007 for (size_t i = 0; i < ARRAY_SIZE(oid); i++) {
1008 tree[i] = repo_parse_tree_indirect(the_repository, oid[i]);
1009 if (repo_parse_tree(the_repository, tree[i]) < 0)
1010 die(_("failed to parse tree"));
1011 init_tree_desc(&tree_desc[i], &tree[i]->object.oid,
1012 tree[i]->buffer, tree[i]->size);
1013 }
1014
1015 unpack_tree_opt.head_idx = -1;
1016 unpack_tree_opt.src_index = the_repository->index;
1017 unpack_tree_opt.dst_index = the_repository->index;
1018 unpack_tree_opt.merge = 1;
1019 unpack_tree_opt.fn = stash_worktree_untracked_merge;
1020
1021 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
1022 die(_("failed to unpack trees"));
1023
1024 do_diff_cache(&info->b_commit, diff_opt);
1025 }
1026
1027 static int show_stash(int argc, const char **argv, const char *prefix,
1028 struct repository *repo UNUSED)
1029 {
1030 int i;
1031 int ret = -1;
1032 struct stash_info info = STASH_INFO_INIT;
1033 struct rev_info rev;
1034 struct strvec stash_args = STRVEC_INIT;
1035 struct strvec revision_args = STRVEC_INIT;
1036 enum {
1037 UNTRACKED_NONE,
1038 UNTRACKED_INCLUDE,
1039 UNTRACKED_ONLY
1040 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
1041 struct option options[] = {
1042 OPT_SET_INT('u', "include-untracked", &show_untracked,
1043 N_("include untracked files in the stash"),
1044 UNTRACKED_INCLUDE),
1045 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
1046 N_("only show untracked files in the stash"),
1047 UNTRACKED_ONLY, PARSE_OPT_NONEG),
1048 OPT_END()
1049 };
1050 int do_usage = 0;
1051
1052 init_diff_ui_defaults();
1053 repo_config(the_repository, git_diff_ui_config, NULL);
1054 repo_init_revisions(the_repository, &rev, prefix);
1055
1056 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
1057 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
1058 PARSE_OPT_KEEP_DASHDASH);
1059
1060 strvec_push(&revision_args, argv[0]);
1061 for (i = 1; i < argc; i++) {
1062 if (argv[i][0] != '-')
1063 strvec_push(&stash_args, argv[i]);
1064 else
1065 strvec_push(&revision_args, argv[i]);
1066 }
1067
1068 if (get_stash_info(&info, stash_args.nr, stash_args.v))
1069 goto cleanup;
1070
1071 /*
1072 * The config settings are applied only if there are not passed
1073 * any options.
1074 */
1075 if (revision_args.nr == 1) {
1076 if (show_stat)
1077 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
1078
1079 if (show_patch)
1080 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1081
1082 if (!show_stat && !show_patch) {
1083 ret = 0;
1084 goto cleanup;
1085 }
1086 }
1087
1088 setup_revisions_from_strvec(&revision_args, &rev, NULL);
1089 if (revision_args.nr > 1)
1090 goto usage;
1091 if (!rev.diffopt.output_format) {
1092 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
1093 diff_setup_done(&rev.diffopt);
1094 }
1095
1096 rev.diffopt.flags.recursive = 1;
1097 setup_diff_pager(&rev.diffopt);
1098 switch (show_untracked) {
1099 case UNTRACKED_NONE:
1100 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
1101 break;
1102 case UNTRACKED_ONLY:
1103 if (info.has_u)
1104 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
1105 break;
1106 case UNTRACKED_INCLUDE:
1107 if (info.has_u)
1108 diff_include_untracked(&info, &rev.diffopt);
1109 else
1110 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
1111 break;
1112 }
1113 log_tree_diff_flush(&rev);
1114
1115 ret = diff_result_code(&rev);
1116
1117 cleanup:
1118 strvec_clear(&revision_args);
1119 strvec_clear(&stash_args);
1120 free_stash_info(&info);
1121 release_revisions(&rev);
1122 if (do_usage)
1123 usage_with_options(git_stash_show_usage, options);
1124 return ret;
1125 usage:
1126 do_usage = 1;
1127 goto cleanup;
1128 }
1129
1130 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
1131 int quiet)
1132 {
1133 struct stash_info info;
1134 char revision[GIT_MAX_HEXSZ];
1135
1136 oid_to_hex_r(revision, w_commit);
1137 assert_stash_like(&info, revision);
1138
1139 if (!stash_msg)
1140 stash_msg = "Created via \"git stash store\".";
1141
1142 if (refs_update_ref(get_main_ref_store(the_repository), stash_msg, ref_stash, w_commit, NULL,
1143 REF_FORCE_CREATE_REFLOG,
1144 quiet ? UPDATE_REFS_QUIET_ON_ERR :
1145 UPDATE_REFS_MSG_ON_ERR)) {
1146 if (!quiet) {
1147 fprintf_ln(stderr, _("Cannot update %s with %s"),
1148 ref_stash, oid_to_hex(w_commit));
1149 }
1150 return -1;
1151 }
1152
1153 return 0;
1154 }
1155
1156 static int store_stash(int argc, const char **argv, const char *prefix,
1157 struct repository *repo UNUSED)
1158 {
1159 int quiet = 0;
1160 const char *stash_msg = NULL;
1161 struct object_id obj;
1162 struct option options[] = {
1163 OPT__QUIET(&quiet, N_("be quiet")),
1164 OPT_STRING('m', "message", &stash_msg, "message",
1165 N_("stash message")),
1166 OPT_END()
1167 };
1168 int ret;
1169
1170 argc = parse_options(argc, argv, prefix, options,
1171 git_stash_store_usage,
1172 PARSE_OPT_KEEP_UNKNOWN_OPT);
1173
1174 if (argc != 1) {
1175 if (!quiet)
1176 fprintf_ln(stderr, _("\"git stash store\" requires one "
1177 "<commit> argument"));
1178 return -1;
1179 }
1180
1181 if (repo_get_oid_with_flags(the_repository, argv[0], &obj,
1182 quiet ? GET_OID_QUIETLY : 0)) {
1183 if (!quiet)
1184 fprintf_ln(stderr, _("Cannot update %s with %s"),
1185 ref_stash, argv[0]);
1186 ret = -1;
1187 goto out;
1188 }
1189
1190 ret = do_store_stash(&obj, stash_msg, quiet);
1191
1192 out:
1193 return ret;
1194 }
1195
1196 static void add_pathspecs(struct strvec *args,
1197 const struct pathspec *ps) {
1198 int i;
1199
1200 for (i = 0; i < ps->nr; i++)
1201 strvec_push(args, ps->items[i].original);
1202 }
1203
1204 /*
1205 * `untracked_files` will be filled with the names of untracked files.
1206 * The return value is:
1207 *
1208 * = 0 if there are not any untracked files
1209 * > 0 if there are untracked files
1210 */
1211 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1212 struct strbuf *untracked_files)
1213 {
1214 int i;
1215 int found = 0;
1216 struct dir_struct dir = DIR_INIT;
1217
1218 if (include_untracked != INCLUDE_ALL_FILES)
1219 setup_standard_excludes(&dir);
1220
1221 fill_directory(&dir, the_repository->index, ps);
1222 for (i = 0; i < dir.nr; i++) {
1223 struct dir_entry *ent = dir.entries[i];
1224 found++;
1225 strbuf_addstr(untracked_files, ent->name);
1226 /* NUL-terminate: will be fed to update-index -z */
1227 strbuf_addch(untracked_files, '\0');
1228 }
1229
1230 dir_clear(&dir);
1231 return found;
1232 }
1233
1234 /*
1235 * The return value of `check_changes_tracked_files()` can be:
1236 *
1237 * < 0 if there was an error
1238 * = 0 if there are no changes.
1239 * > 0 if there are changes.
1240 */
1241 static int check_changes_tracked_files(const struct pathspec *ps)
1242 {
1243 struct rev_info rev;
1244 struct object_id dummy;
1245 int ret = 0;
1246
1247 /* No initial commit. */
1248 if (repo_get_oid(the_repository, "HEAD", &dummy))
1249 return -1;
1250
1251 if (repo_read_index(the_repository) < 0)
1252 return -1;
1253
1254 repo_init_revisions(the_repository, &rev, NULL);
1255 copy_pathspec(&rev.prune_data, ps);
1256
1257 rev.diffopt.flags.quick = 1;
1258 rev.diffopt.flags.ignore_submodules = 1;
1259 rev.abbrev = 0;
1260
1261 add_head_to_pending(&rev);
1262 diff_setup_done(&rev.diffopt);
1263
1264 run_diff_index(&rev, DIFF_INDEX_CACHED);
1265 if (diff_result_code(&rev)) {
1266 ret = 1;
1267 goto done;
1268 }
1269
1270 run_diff_files(&rev, 0);
1271 if (diff_result_code(&rev)) {
1272 ret = 1;
1273 goto done;
1274 }
1275
1276 done:
1277 release_revisions(&rev);
1278 return ret;
1279 }
1280
1281 /*
1282 * The function will fill `untracked_files` with the names of untracked files
1283 * It will return 1 if there were any changes and 0 if there were not.
1284 */
1285 static int check_changes(const struct pathspec *ps, int include_untracked,
1286 struct strbuf *untracked_files)
1287 {
1288 int ret = 0;
1289 if (check_changes_tracked_files(ps))
1290 ret = 1;
1291
1292 if (include_untracked && get_untracked_files(ps, include_untracked,
1293 untracked_files))
1294 ret = 1;
1295
1296 return ret;
1297 }
1298
1299 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1300 struct strbuf *files)
1301 {
1302 int ret = 0;
1303 struct strbuf untracked_msg = STRBUF_INIT;
1304 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1305 struct index_state istate = INDEX_STATE_INIT(the_repository);
1306
1307 cp_upd_index.git_cmd = 1;
1308 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1309 "--remove", "--stdin", NULL);
1310 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1311 stash_index_path.buf);
1312
1313 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1314 if (pipe_command(&cp_upd_index, files->buf, files->len, NULL, 0,
1315 NULL, 0)) {
1316 ret = -1;
1317 goto done;
1318 }
1319
1320 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1321 NULL)) {
1322 ret = -1;
1323 goto done;
1324 }
1325
1326 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1327 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1328 ret = -1;
1329 goto done;
1330 }
1331
1332 done:
1333 release_index(&istate);
1334 strbuf_release(&untracked_msg);
1335 remove_path(stash_index_path.buf);
1336 return ret;
1337 }
1338
1339 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1340 int quiet)
1341 {
1342 int ret = 0;
1343 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1344 struct index_state istate = INDEX_STATE_INIT(the_repository);
1345
1346 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1347 0, NULL)) {
1348 ret = -1;
1349 goto done;
1350 }
1351
1352 cp_diff_tree.git_cmd = 1;
1353 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "--binary",
1354 "--no-color",
1355 "-U1", "HEAD", oid_to_hex(&info->w_tree), "--", NULL);
1356 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1357 ret = -1;
1358 goto done;
1359 }
1360
1361 if (!out_patch->len) {
1362 if (!quiet)
1363 fprintf_ln(stderr, _("No staged changes"));
1364 ret = 1;
1365 }
1366
1367 done:
1368 release_index(&istate);
1369 return ret;
1370 }
1371
1372 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1373 struct strbuf *out_patch, int quiet,
1374 struct interactive_options *interactive_opts)
1375 {
1376 int ret = 0;
1377 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1378 struct commit *head_commit;
1379 const struct object_id *head_tree;
1380 struct index_state istate = INDEX_STATE_INIT(the_repository);
1381 char *old_index_env = NULL, *old_repo_index_file;
1382
1383 remove_path(stash_index_path.buf);
1384
1385 head_commit = lookup_commit(the_repository, &info->b_commit);
1386 if (!head_commit || repo_parse_commit(the_repository, head_commit)) {
1387 ret = -1;
1388 goto done;
1389 }
1390 head_tree = get_commit_tree_oid(head_commit);
1391 if (!head_tree) {
1392 ret = -1;
1393 goto done;
1394 }
1395
1396 if (create_index_from_tree(head_tree, stash_index_path.buf)) {
1397 ret = -1;
1398 goto done;
1399 }
1400
1401 /* Find out what the user wants. */
1402 old_repo_index_file = the_repository->index_file;
1403 the_repository->index_file = stash_index_path.buf;
1404 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1405 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1406
1407 ret = !!run_add_p(the_repository, ADD_P_STASH, interactive_opts, NULL, ps, 0);
1408
1409 the_repository->index_file = old_repo_index_file;
1410 if (old_index_env && *old_index_env)
1411 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1412 else
1413 unsetenv(INDEX_ENVIRONMENT);
1414 FREE_AND_NULL(old_index_env);
1415
1416 /* State of the working tree. */
1417 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1418 NULL)) {
1419 ret = -1;
1420 goto done;
1421 }
1422
1423 cp_diff_tree.git_cmd = 1;
1424 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1425 "--no-color",
1426 oid_to_hex(&info->w_tree), "--", NULL);
1427 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1428 ret = -1;
1429 goto done;
1430 }
1431
1432 if (!out_patch->len) {
1433 if (!quiet)
1434 fprintf_ln(stderr, _("No changes selected"));
1435 ret = 1;
1436 }
1437
1438 done:
1439 release_index(&istate);
1440 remove_path(stash_index_path.buf);
1441 return ret;
1442 }
1443
1444 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1445 {
1446 int ret = 0;
1447 struct rev_info rev;
1448 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1449 struct strbuf diff_output = STRBUF_INIT;
1450 struct index_state istate = INDEX_STATE_INIT(the_repository);
1451
1452 repo_init_revisions(the_repository, &rev, NULL);
1453 copy_pathspec(&rev.prune_data, ps);
1454
1455 set_alternate_index_output(stash_index_path.buf);
1456 if (reset_tree(&info->i_tree, 0, 0)) {
1457 ret = -1;
1458 goto done;
1459 }
1460 set_alternate_index_output(NULL);
1461
1462 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1463 rev.diffopt.format_callback = add_diff_to_buf;
1464 rev.diffopt.format_callback_data = &diff_output;
1465
1466 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1467 ret = -1;
1468 goto done;
1469 }
1470
1471 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1472 "");
1473 run_diff_index(&rev, 0);
1474
1475 cp_upd_index.git_cmd = 1;
1476 strvec_pushl(&cp_upd_index.args, "update-index",
1477 "--ignore-skip-worktree-entries",
1478 "-z", "--add", "--remove", "--stdin", NULL);
1479 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1480 stash_index_path.buf);
1481
1482 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1483 NULL, 0, NULL, 0)) {
1484 ret = -1;
1485 goto done;
1486 }
1487
1488 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1489 NULL)) {
1490 ret = -1;
1491 goto done;
1492 }
1493
1494 done:
1495 release_index(&istate);
1496 release_revisions(&rev);
1497 strbuf_release(&diff_output);
1498 remove_path(stash_index_path.buf);
1499 return ret;
1500 }
1501
1502 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1503 int include_untracked, int patch_mode,
1504 struct interactive_options *interactive_opts,
1505 int only_staged, struct stash_info *info, struct strbuf *patch,
1506 int quiet)
1507 {
1508 int ret = 0;
1509 int flags = 0;
1510 int untracked_commit_option = 0;
1511 const char *head_short_sha1 = NULL;
1512 const char *branch_ref = NULL;
1513 const char *branch_name = "(no branch)";
1514 char *branch_name_buf = NULL;
1515 struct commit *head_commit = NULL;
1516 struct commit_list *parents = NULL;
1517 struct strbuf msg = STRBUF_INIT;
1518 struct strbuf commit_tree_label = STRBUF_INIT;
1519 struct strbuf untracked_files = STRBUF_INIT;
1520
1521 prepare_fallback_ident("git stash", "git@stash");
1522
1523 repo_read_index_preload(the_repository, NULL, 0);
1524 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1525 NULL, NULL, NULL) < 0) {
1526 ret = error(_("could not write index"));
1527 goto done;
1528 }
1529
1530 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1531 if (!quiet)
1532 fprintf_ln(stderr, _("You do not have "
1533 "the initial commit yet"));
1534 ret = -1;
1535 goto done;
1536 } else {
1537 head_commit = lookup_commit(the_repository, &info->b_commit);
1538 }
1539
1540 if (!check_changes(ps, include_untracked, &untracked_files)) {
1541 ret = 1;
1542 goto done;
1543 }
1544
1545 branch_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1546 "HEAD", 0, NULL, &flags);
1547
1548 if (flags & REF_ISSYMREF) {
1549 if (skip_prefix(branch_ref, "refs/heads/", &branch_name))
1550 branch_name = branch_name_buf = xstrdup(branch_name);
1551 }
1552
1553 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1554 &head_commit->object.oid,
1555 DEFAULT_ABBREV);
1556 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1557 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1558
1559 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1560 commit_list_insert(head_commit, &parents);
1561 if (write_index_as_tree(&info->i_tree, the_repository->index,
1562 repo_get_index_file(the_repository), 0, NULL) ||
1563 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1564 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1565 if (!quiet)
1566 fprintf_ln(stderr, _("Cannot save the current "
1567 "index state"));
1568 ret = -1;
1569 goto done;
1570 }
1571
1572 commit_list_free(parents);
1573 parents = NULL;
1574
1575 if (include_untracked) {
1576 if (save_untracked_files(info, &msg, &untracked_files)) {
1577 if (!quiet)
1578 fprintf_ln(stderr, _("Cannot save "
1579 "the untracked files"));
1580 ret = -1;
1581 goto done;
1582 }
1583 untracked_commit_option = 1;
1584 }
1585 if (patch_mode) {
1586 ret = stash_patch(info, ps, patch, quiet, interactive_opts);
1587 if (ret < 0) {
1588 if (!quiet)
1589 fprintf_ln(stderr, _("Cannot save the current "
1590 "worktree state"));
1591 goto done;
1592 } else if (ret > 0) {
1593 goto done;
1594 }
1595 } else if (only_staged) {
1596 ret = stash_staged(info, patch, quiet);
1597 if (ret < 0) {
1598 if (!quiet)
1599 fprintf_ln(stderr, _("Cannot save the current "
1600 "staged state"));
1601 goto done;
1602 } else if (ret > 0) {
1603 goto done;
1604 }
1605 } else {
1606 if (stash_working_tree(info, ps)) {
1607 if (!quiet)
1608 fprintf_ln(stderr, _("Cannot save the current "
1609 "worktree state"));
1610 ret = -1;
1611 goto done;
1612 }
1613 }
1614
1615 if (!stash_msg_buf->len)
1616 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1617 else
1618 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1619
1620 if (untracked_commit_option)
1621 commit_list_insert(lookup_commit(the_repository,
1622 &info->u_commit),
1623 &parents);
1624 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1625 &parents);
1626 commit_list_insert(head_commit, &parents);
1627
1628 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1629 parents, &info->w_commit, NULL, NULL)) {
1630 if (!quiet)
1631 fprintf_ln(stderr, _("Cannot record "
1632 "working tree state"));
1633 ret = -1;
1634 goto done;
1635 }
1636
1637 done:
1638 strbuf_release(&commit_tree_label);
1639 strbuf_release(&msg);
1640 strbuf_release(&untracked_files);
1641 commit_list_free(parents);
1642 free(branch_name_buf);
1643 return ret;
1644 }
1645
1646 static int create_stash(int argc, const char **argv, const char *prefix UNUSED,
1647 struct repository *repo UNUSED)
1648 {
1649 int ret;
1650 struct strbuf stash_msg_buf = STRBUF_INIT;
1651 struct stash_info info = STASH_INFO_INIT;
1652 struct pathspec ps;
1653
1654 /* Starting with argv[1], since argv[0] is "create" */
1655 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1656
1657 memset(&ps, 0, sizeof(ps));
1658 if (!check_changes_tracked_files(&ps))
1659 return 0;
1660
1661 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, NULL, 0, &info,
1662 NULL, 0);
1663 if (!ret)
1664 printf_ln("%s", oid_to_hex(&info.w_commit));
1665
1666 free_stash_info(&info);
1667 strbuf_release(&stash_msg_buf);
1668 return ret;
1669 }
1670
1671 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1672 int keep_index, int patch_mode,
1673 struct interactive_options *interactive_opts,
1674 int include_untracked, int only_staged)
1675 {
1676 int ret = 0;
1677 struct stash_info info = STASH_INFO_INIT;
1678 struct strbuf patch = STRBUF_INIT;
1679 struct strbuf stash_msg_buf = STRBUF_INIT;
1680 struct strbuf untracked_files = STRBUF_INIT;
1681 struct strbuf out = STRBUF_INIT;
1682
1683 if (patch_mode && keep_index == -1)
1684 keep_index = 1;
1685
1686 if (patch_mode && include_untracked) {
1687 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1688 " or --all at the same time"));
1689 ret = -1;
1690 goto done;
1691 }
1692
1693 /* --patch overrides --staged */
1694 if (patch_mode)
1695 only_staged = 0;
1696
1697 if (only_staged && include_untracked) {
1698 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1699 " or --all at the same time"));
1700 ret = -1;
1701 goto done;
1702 }
1703
1704 repo_read_index_preload(the_repository, NULL, 0);
1705 if (!include_untracked && ps->nr) {
1706 char *ps_matched = xcalloc(ps->nr, 1);
1707
1708 if (pathspec_needs_expanded_index(the_repository->index, ps))
1709 ensure_full_index(the_repository->index);
1710 for (size_t i = 0; i < the_repository->index->cache_nr; i++)
1711 ce_path_match(the_repository->index, the_repository->index->cache[i], ps,
1712 ps_matched);
1713
1714 if (report_path_error(ps_matched, ps)) {
1715 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1716 ret = -1;
1717 free(ps_matched);
1718 goto done;
1719 }
1720 free(ps_matched);
1721 }
1722
1723 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1724 NULL, NULL, NULL)) {
1725 ret = error(_("could not write index"));
1726 goto done;
1727 }
1728
1729 if (!check_changes(ps, include_untracked, &untracked_files)) {
1730 if (!quiet)
1731 printf_ln(_("No local changes to save"));
1732 goto done;
1733 }
1734
1735 if (!refs_reflog_exists(get_main_ref_store(the_repository), ref_stash) && do_clear_stash()) {
1736 ret = -1;
1737 if (!quiet)
1738 fprintf_ln(stderr, _("Cannot initialize stash"));
1739 goto done;
1740 }
1741
1742 if (stash_msg)
1743 strbuf_addstr(&stash_msg_buf, stash_msg);
1744 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1745 interactive_opts, only_staged, &info, &patch, quiet)) {
1746 ret = -1;
1747 goto done;
1748 }
1749
1750 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1751 ret = -1;
1752 if (!quiet)
1753 fprintf_ln(stderr, _("Cannot save the current status"));
1754 goto done;
1755 }
1756
1757 if (!quiet)
1758 printf_ln(_("Saved working directory and index state %s"),
1759 stash_msg_buf.buf);
1760
1761 if (!(patch_mode || only_staged)) {
1762 if (include_untracked && !ps->nr) {
1763 struct child_process cp = CHILD_PROCESS_INIT;
1764
1765 cp.git_cmd = 1;
1766 if (startup_info->original_cwd) {
1767 cp.dir = startup_info->original_cwd;
1768 strvec_pushf(&cp.env, "%s=%s",
1769 GIT_WORK_TREE_ENVIRONMENT,
1770 the_repository->worktree);
1771 }
1772 strvec_pushl(&cp.args, "clean", "--force",
1773 "--quiet", "-d", ":/", NULL);
1774 if (include_untracked == INCLUDE_ALL_FILES)
1775 strvec_push(&cp.args, "-x");
1776 if (run_command(&cp)) {
1777 ret = -1;
1778 goto done;
1779 }
1780 }
1781 discard_index(the_repository->index);
1782 if (ps->nr) {
1783 struct child_process cp_add = CHILD_PROCESS_INIT;
1784 struct child_process cp_diff = CHILD_PROCESS_INIT;
1785 struct child_process cp_apply = CHILD_PROCESS_INIT;
1786
1787 cp_add.git_cmd = 1;
1788 strvec_push(&cp_add.args, "add");
1789 if (!include_untracked)
1790 strvec_push(&cp_add.args, "-u");
1791 if (include_untracked == INCLUDE_ALL_FILES)
1792 strvec_push(&cp_add.args, "--force");
1793 strvec_push(&cp_add.args, "--");
1794 add_pathspecs(&cp_add.args, ps);
1795 if (run_command(&cp_add)) {
1796 ret = -1;
1797 goto done;
1798 }
1799
1800 cp_diff.git_cmd = 1;
1801 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1802 "--no-color",
1803 "--cached", "--binary", "HEAD", "--",
1804 NULL);
1805 add_pathspecs(&cp_diff.args, ps);
1806 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1807 ret = -1;
1808 goto done;
1809 }
1810
1811 cp_apply.git_cmd = 1;
1812 strvec_pushl(&cp_apply.args, "apply", "--index",
1813 "-R", NULL);
1814 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1815 NULL, 0)) {
1816 ret = -1;
1817 goto done;
1818 }
1819 } else {
1820 struct child_process cp = CHILD_PROCESS_INIT;
1821 cp.git_cmd = 1;
1822 /* BUG: this nukes untracked files in the way */
1823 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1824 "--no-recurse-submodules", NULL);
1825 if (run_command(&cp)) {
1826 ret = -1;
1827 goto done;
1828 }
1829 }
1830
1831 /*
1832 * When keeping staged entries, we need to reset the working
1833 * directory to match the state of our index. This can be
1834 * skipped when the index is the empty tree, because there is
1835 * nothing to reset in that case:
1836 *
1837 * - When the index has any file, regardless of whether
1838 * staged or not, the tree cannot be empty by definition
1839 * and thus we enter the condition.
1840 *
1841 * - When the index has no files, the only thing we need to
1842 * care about is untracked files when `--include-untracked`
1843 * is given. But as we already execute git-clean(1) further
1844 * up to delete such untracked files we don't have to do
1845 * anything here, either.
1846 *
1847 * We thus skip calling git-checkout(1) in this case, also
1848 * because running it on an empty tree will cause it to fail
1849 * due to the pathspec not matching anything.
1850 */
1851 if (keep_index == 1 && !is_null_oid(&info.i_tree) &&
1852 !is_empty_tree_oid(&info.i_tree, the_repository->hash_algo)) {
1853 struct child_process cp = CHILD_PROCESS_INIT;
1854
1855 cp.git_cmd = 1;
1856 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1857 oid_to_hex(&info.i_tree), "--", NULL);
1858 if (!ps->nr)
1859 strvec_push(&cp.args, ":/");
1860 else
1861 add_pathspecs(&cp.args, ps);
1862 if (run_command(&cp)) {
1863 ret = -1;
1864 goto done;
1865 }
1866 }
1867 goto done;
1868 } else {
1869 struct child_process cp = CHILD_PROCESS_INIT;
1870
1871 cp.git_cmd = 1;
1872 strvec_pushl(&cp.args, "apply", "-R", NULL);
1873
1874 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1875 if (!quiet)
1876 fprintf_ln(stderr, _("Cannot remove "
1877 "worktree changes"));
1878 ret = -1;
1879 goto done;
1880 }
1881
1882 if (keep_index < 1) {
1883 struct child_process cp = CHILD_PROCESS_INIT;
1884
1885 cp.git_cmd = 1;
1886 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1887 NULL);
1888 add_pathspecs(&cp.args, ps);
1889 if (run_command(&cp)) {
1890 ret = -1;
1891 goto done;
1892 }
1893 }
1894 goto done;
1895 }
1896
1897 done:
1898 strbuf_release(&patch);
1899 strbuf_release(&out);
1900 free_stash_info(&info);
1901 strbuf_release(&stash_msg_buf);
1902 strbuf_release(&untracked_files);
1903 return ret;
1904 }
1905
1906 static int push_stash(int argc, const char **argv, const char *prefix,
1907 int push_assumed)
1908 {
1909 int force_assume = 0;
1910 int keep_index = -1;
1911 int only_staged = 0;
1912 int patch_mode = 0;
1913 int include_untracked = 0;
1914 int quiet = 0;
1915 int pathspec_file_nul = 0;
1916 const char *stash_msg = NULL;
1917 char *pathspec_from_file = NULL;
1918 struct pathspec ps;
1919 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
1920 struct option options[] = {
1921 OPT_BOOL('k', "keep-index", &keep_index,
1922 N_("keep index")),
1923 OPT_BOOL('S', "staged", &only_staged,
1924 N_("stash staged changes only")),
1925 OPT_BOOL('p', "patch", &patch_mode,
1926 N_("stash in patch mode")),
1927 OPT_BOOL(0, "auto-advance", &interactive_opts.auto_advance,
1928 N_("auto advance to the next file when selecting hunks interactively")),
1929 OPT_DIFF_UNIFIED(&interactive_opts.context),
1930 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
1931 OPT__QUIET(&quiet, N_("quiet mode")),
1932 OPT_BOOL('u', "include-untracked", &include_untracked,
1933 N_("include untracked files in stash")),
1934 OPT_SET_INT('a', "all", &include_untracked,
1935 N_("include ignore files"), 2),
1936 OPT_STRING('m', "message", &stash_msg, N_("message"),
1937 N_("stash message")),
1938 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1939 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1940 OPT_END()
1941 };
1942 int ret;
1943
1944 if (argc) {
1945 int flags = PARSE_OPT_KEEP_DASHDASH;
1946
1947 if (push_assumed)
1948 flags |= PARSE_OPT_STOP_AT_NON_OPTION;
1949
1950 argc = parse_options(argc, argv, prefix, options,
1951 push_assumed ? git_stash_usage :
1952 git_stash_push_usage, flags);
1953 force_assume |= patch_mode;
1954 }
1955
1956 if (argc) {
1957 if (!strcmp(argv[0], "--")) {
1958 argc--;
1959 argv++;
1960 } else if (push_assumed && !force_assume) {
1961 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1962 argv[0]);
1963 }
1964 }
1965
1966 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1967 prefix, argv);
1968
1969 if (pathspec_from_file) {
1970 if (patch_mode)
1971 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1972
1973 if (only_staged)
1974 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1975
1976 if (ps.nr)
1977 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1978
1979 parse_pathspec_file(&ps, 0,
1980 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1981 prefix, pathspec_from_file, pathspec_file_nul);
1982 } else if (pathspec_file_nul) {
1983 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1984 }
1985
1986 if (!patch_mode) {
1987 if (interactive_opts.context != -1)
1988 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
1989 if (interactive_opts.interhunkcontext != -1)
1990 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
1991 if (!interactive_opts.auto_advance)
1992 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
1993 }
1994
1995 if (interactive_opts.context < -1)
1996 die(_("'%s' cannot be negative"), "--unified");
1997 if (interactive_opts.interhunkcontext < -1)
1998 die(_("'%s' cannot be negative"), "--inter-hunk-context");
1999
2000 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
2001 &interactive_opts, include_untracked, only_staged);
2002
2003 clear_pathspec(&ps);
2004 free(pathspec_from_file);
2005 return ret;
2006 }
2007
2008 static int push_stash_unassumed(int argc, const char **argv, const char *prefix,
2009 struct repository *repo UNUSED)
2010 {
2011 return push_stash(argc, argv, prefix, 0);
2012 }
2013
2014 static int save_stash(int argc, const char **argv, const char *prefix,
2015 struct repository *repo UNUSED)
2016 {
2017 int keep_index = -1;
2018 int only_staged = 0;
2019 int patch_mode = 0;
2020 int include_untracked = 0;
2021 int quiet = 0;
2022 int ret = 0;
2023 const char *stash_msg = NULL;
2024 struct pathspec ps;
2025 struct strbuf stash_msg_buf = STRBUF_INIT;
2026 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
2027 struct option options[] = {
2028 OPT_BOOL('k', "keep-index", &keep_index,
2029 N_("keep index")),
2030 OPT_BOOL('S', "staged", &only_staged,
2031 N_("stash staged changes only")),
2032 OPT_BOOL('p', "patch", &patch_mode,
2033 N_("stash in patch mode")),
2034 OPT_BOOL(0, "auto-advance", &interactive_opts.auto_advance,
2035 N_("auto advance to the next file when selecting hunks interactively")),
2036 OPT_DIFF_UNIFIED(&interactive_opts.context),
2037 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
2038 OPT__QUIET(&quiet, N_("quiet mode")),
2039 OPT_BOOL('u', "include-untracked", &include_untracked,
2040 N_("include untracked files in stash")),
2041 OPT_SET_INT('a', "all", &include_untracked,
2042 N_("include ignore files"), 2),
2043 OPT_STRING('m', "message", &stash_msg, "message",
2044 N_("stash message")),
2045 OPT_END()
2046 };
2047
2048 argc = parse_options(argc, argv, prefix, options,
2049 git_stash_save_usage,
2050 PARSE_OPT_KEEP_DASHDASH);
2051
2052 if (argc)
2053 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
2054
2055 memset(&ps, 0, sizeof(ps));
2056
2057 if (interactive_opts.context < -1)
2058 die(_("'%s' cannot be negative"), "--unified");
2059 if (interactive_opts.interhunkcontext < -1)
2060 die(_("'%s' cannot be negative"), "--inter-hunk-context");
2061
2062 if (!patch_mode) {
2063 if (interactive_opts.context != -1)
2064 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
2065 if (interactive_opts.interhunkcontext != -1)
2066 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
2067 if (!interactive_opts.auto_advance)
2068 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
2069 }
2070
2071 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
2072 patch_mode, &interactive_opts, include_untracked,
2073 only_staged);
2074
2075 strbuf_release(&stash_msg_buf);
2076 return ret;
2077 }
2078
2079 static int write_commit_with_parents(struct repository *r,
2080 struct object_id *out,
2081 const struct object_id *oid,
2082 struct commit_list *parents)
2083 {
2084 size_t author_len, committer_len;
2085 struct commit *this;
2086 const char *orig_author, *orig_committer;
2087 char *author = NULL, *committer = NULL;
2088 const char *buffer;
2089 unsigned long bufsize;
2090 const char *p;
2091 struct strbuf msg = STRBUF_INIT;
2092 int ret = 0;
2093 struct ident_split id;
2094
2095 this = lookup_commit_reference(r, oid);
2096 buffer = repo_get_commit_buffer(r, this, &bufsize);
2097 orig_author = find_commit_header(buffer, "author", &author_len);
2098 orig_committer = find_commit_header(buffer, "committer", &committer_len);
2099
2100 if (!orig_author || !orig_committer) {
2101 ret = error(_("cannot parse commit %s"), oid_to_hex(oid));
2102 goto out;
2103 }
2104
2105 if (split_ident_line(&id, orig_author, author_len) < 0 ||
2106 split_ident_line(&id, orig_committer, committer_len) < 0) {
2107 ret = error(_("invalid author or committer for %s"), oid_to_hex(oid));
2108 goto out;
2109 }
2110
2111 p = strstr(buffer, "\n\n");
2112 strbuf_addstr(&msg, "git stash: ");
2113
2114 if (p)
2115 strbuf_add(&msg, p + 2, bufsize - (p + 2 - buffer));
2116 strbuf_complete_line(&msg);
2117
2118 author = xmemdupz(orig_author, author_len);
2119 committer = xmemdupz(orig_committer, committer_len);
2120
2121 if (commit_tree_extended(msg.buf, msg.len,
2122 r->hash_algo->empty_tree, parents,
2123 out, author, committer,
2124 NULL, NULL)) {
2125 ret = error(_("could not write commit"));
2126 goto out;
2127 }
2128 out:
2129 strbuf_release(&msg);
2130 repo_unuse_commit_buffer(r, this, buffer);
2131 free(author);
2132 free(committer);
2133 return ret;
2134 }
2135
2136 static int do_import_stash(struct repository *r, const char *rev)
2137 {
2138 struct object_id chain;
2139 int res = 0;
2140 const char *buffer = NULL;
2141 unsigned long bufsize;
2142 struct commit *this = NULL;
2143 struct commit_list *items = NULL, *cur;
2144 char *msg = NULL;
2145
2146 if (repo_get_oid(r, rev, &chain))
2147 return error(_("not a valid revision: %s"), rev);
2148
2149 this = lookup_commit_reference(r, &chain);
2150 if (!this)
2151 return error(_("not a commit: %s"), rev);
2152
2153 /*
2154 * Walk the commit history, finding each stash entry, and load data into
2155 * the array.
2156 */
2157 for (;;) {
2158 const char *author, *committer;
2159 size_t author_len, committer_len;
2160 const char *p;
2161 const char *expected = "git stash <git@stash> 1000684800 +0000";
2162 const char *prefix = "git stash: ";
2163 struct commit *stash;
2164 struct tree *tree = repo_get_commit_tree(r, this);
2165
2166 if (!tree ||
2167 !oideq(&tree->object.oid, r->hash_algo->empty_tree) ||
2168 (this->parents &&
2169 (!this->parents->next || this->parents->next->next))) {
2170 res = error(_("%s is not a valid exported stash commit"),
2171 oid_to_hex(&this->object.oid));
2172 goto out;
2173 }
2174
2175 buffer = repo_get_commit_buffer(r, this, &bufsize);
2176
2177 if (!this->parents) {
2178 /*
2179 * We don't have any parents. Make sure this is our
2180 * root commit.
2181 */
2182 author = find_commit_header(buffer, "author", &author_len);
2183 committer = find_commit_header(buffer, "committer", &committer_len);
2184
2185 if (!author || !committer) {
2186 error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2187 goto out;
2188 }
2189
2190 if (author_len != strlen(expected) ||
2191 committer_len != strlen(expected) ||
2192 memcmp(author, expected, author_len) ||
2193 memcmp(committer, expected, committer_len)) {
2194 res = error(_("found root commit %s with invalid data"), oid_to_hex(&this->object.oid));
2195 goto out;
2196 }
2197 break;
2198 }
2199
2200 p = strstr(buffer, "\n\n");
2201 if (!p) {
2202 res = error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2203 goto out;
2204 }
2205
2206 p += 2;
2207 if (((size_t)(bufsize - (p - buffer)) < strlen(prefix)) ||
2208 memcmp(prefix, p, strlen(prefix))) {
2209 res = error(_("found stash commit %s without expected prefix"), oid_to_hex(&this->object.oid));
2210 goto out;
2211 }
2212
2213 stash = this->parents->next->item;
2214
2215 if (repo_parse_commit(r, this->parents->item) ||
2216 repo_parse_commit(r, stash)) {
2217 res = error(_("cannot parse parents of commit: %s"),
2218 oid_to_hex(&this->object.oid));
2219 goto out;
2220 }
2221
2222 if (check_stash_topology(r, stash)) {
2223 res = error(_("%s does not look like a stash commit"),
2224 oid_to_hex(&stash->object.oid));
2225 goto out;
2226 }
2227
2228 repo_unuse_commit_buffer(r, this, buffer);
2229 buffer = NULL;
2230 items = commit_list_insert(stash, &items);
2231 this = this->parents->item;
2232 }
2233
2234 /*
2235 * Now, walk each entry, adding it to the stash as a normal stash
2236 * commit.
2237 */
2238 for (cur = items; cur; cur = cur->next) {
2239 const char *p;
2240 struct object_id *oid;
2241
2242 this = cur->item;
2243 oid = &this->object.oid;
2244 buffer = repo_get_commit_buffer(r, this, &bufsize);
2245 if (!buffer) {
2246 res = error(_("cannot read commit buffer for %s"), oid_to_hex(oid));
2247 goto out;
2248 }
2249
2250 p = strstr(buffer, "\n\n");
2251 if (!p) {
2252 res = error(_("cannot parse commit %s"), oid_to_hex(oid));
2253 goto out;
2254 }
2255
2256 p += 2;
2257 msg = xmemdupz(p, bufsize - (p - buffer));
2258 repo_unuse_commit_buffer(r, this, buffer);
2259 buffer = NULL;
2260
2261 if (do_store_stash(oid, msg, 1)) {
2262 res = error(_("cannot save the stash for %s"), oid_to_hex(oid));
2263 goto out;
2264 }
2265 FREE_AND_NULL(msg);
2266 }
2267 out:
2268 if (this && buffer)
2269 repo_unuse_commit_buffer(r, this, buffer);
2270 commit_list_free(items);
2271 free(msg);
2272
2273 return res;
2274 }
2275
2276 static int import_stash(int argc, const char **argv, const char *prefix,
2277 struct repository *repo)
2278 {
2279 struct option options[] = {
2280 OPT_END()
2281 };
2282
2283 argc = parse_options(argc, argv, prefix, options,
2284 git_stash_import_usage,
2285 PARSE_OPT_KEEP_DASHDASH);
2286
2287 if (argc != 1)
2288 usage_msg_opt("a revision is required", git_stash_import_usage, options);
2289
2290 return do_import_stash(repo, argv[0]);
2291 }
2292
2293 struct stash_entry_data {
2294 struct repository *r;
2295 struct commit_list **items;
2296 size_t count;
2297 };
2298
2299 static int collect_stash_entries(const char *refname UNUSED,
2300 struct object_id *old_oid UNUSED,
2301 struct object_id *new_oid,
2302 const char *committer UNUSED,
2303 timestamp_t timestamp UNUSED,
2304 int tz UNUSED, const char *msg UNUSED,
2305 void *cb_data)
2306 {
2307 struct stash_entry_data *data = cb_data;
2308 struct commit *stash;
2309
2310 data->count++;
2311 stash = lookup_commit_reference(data->r, new_oid);
2312 if (!stash || check_stash_topology(data->r, stash)) {
2313 return error(_("%s does not look like a stash commit"),
2314 oid_to_hex(new_oid));
2315 }
2316 data->items = commit_list_append(stash, data->items);
2317 return 0;
2318 }
2319
2320 static int do_export_stash(struct repository *r,
2321 const char *ref,
2322 int argc,
2323 const char **argv)
2324 {
2325 struct object_id base;
2326 struct commit *prev;
2327 struct commit_list *items = NULL, **iter = &items, *cur;
2328 int res = 0;
2329 int i;
2330 struct strbuf revision = STRBUF_INIT;
2331 const char *author, *committer;
2332
2333 /*
2334 * This is an arbitrary, fixed date, specifically the one used by git
2335 * format-patch. The goal is merely to produce reproducible output.
2336 */
2337 prepare_fallback_ident("git stash", "git@stash");
2338 author = fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT,
2339 "2001-09-17T00:00:00Z", 0);
2340 committer = fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT,
2341 "2001-09-17T00:00:00Z", 0);
2342
2343 /* First, we create a single empty commit. */
2344 if (commit_tree_extended("", 0, r->hash_algo->empty_tree, NULL,
2345 &base, author, committer, NULL, NULL))
2346 return error(_("unable to write base commit"));
2347
2348 prev = lookup_commit_reference(r, &base);
2349
2350 if (argc) {
2351 /*
2352 * Find each specified stash, and load data into the array.
2353 */
2354 for (i = 0; i < argc; i++) {
2355 struct object_id oid;
2356 struct commit *stash;
2357
2358 if (parse_stash_revision(&revision, argv[i], 1) ||
2359 repo_get_oid_with_flags(r, revision.buf, &oid,
2360 GET_OID_QUIETLY |
2361 GET_OID_GENTLY)) {
2362 res = error(_("unable to find stash entry %s"), argv[i]);
2363 goto out;
2364 }
2365
2366 stash = lookup_commit_reference(r, &oid);
2367 if (!stash || check_stash_topology(r, stash)) {
2368 res = error(_("%s does not look like a stash commit"),
2369 revision.buf);
2370 goto out;
2371 }
2372 iter = commit_list_append(stash, iter);
2373 }
2374 } else {
2375 /*
2376 * Walk the reflog, finding each stash entry, and load data into the
2377 * array.
2378 */
2379 struct stash_entry_data cb_data = {
2380 .r = r, .items = iter,
2381 };
2382 if (refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
2383 "refs/stash",
2384 collect_stash_entries,
2385 &cb_data) && cb_data.count)
2386 goto out;
2387 }
2388
2389 /*
2390 * Now, create a set of commits identical to the regular stash commits,
2391 * but where their first parents form a chain to our original empty
2392 * base commit.
2393 */
2394 items = commit_list_reverse(items);
2395 for (cur = items; cur; cur = cur->next) {
2396 struct commit_list *parents = NULL;
2397 struct commit_list **next = &parents;
2398 struct object_id out;
2399 struct commit *stash = cur->item;
2400
2401 next = commit_list_append(prev, next);
2402 next = commit_list_append(stash, next);
2403 res = write_commit_with_parents(r, &out, &stash->object.oid, parents);
2404 commit_list_free(parents);
2405 if (res)
2406 goto out;
2407 prev = lookup_commit_reference(r, &out);
2408 }
2409 if (ref)
2410 refs_update_ref(get_main_ref_store(r), NULL, ref,
2411 &prev->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
2412 else
2413 puts(oid_to_hex(&prev->object.oid));
2414 out:
2415 strbuf_release(&revision);
2416 commit_list_free(items);
2417
2418 return res;
2419 }
2420
2421 enum export_action {
2422 ACTION_NONE,
2423 ACTION_PRINT,
2424 ACTION_TO_REF,
2425 };
2426
2427 static int export_stash(int argc,
2428 const char **argv,
2429 const char *prefix,
2430 struct repository *repo)
2431 {
2432 const char *ref = NULL;
2433 enum export_action action = ACTION_NONE;
2434 struct option options[] = {
2435 OPT_CMDMODE(0, "print", &action,
2436 N_("print the object ID instead of writing it to a ref"),
2437 ACTION_PRINT),
2438 OPT_STRING(0, "to-ref", &ref, "ref",
2439 N_("save the data to the given ref")),
2440 OPT_END()
2441 };
2442
2443 argc = parse_options(argc, argv, prefix, options,
2444 git_stash_export_usage,
2445 PARSE_OPT_KEEP_DASHDASH);
2446
2447 if (ref && action == ACTION_NONE)
2448 action = ACTION_TO_REF;
2449
2450 if (action == ACTION_NONE || (ref && action == ACTION_PRINT))
2451 return error(_("exactly one of --print and --to-ref is required"));
2452
2453 return do_export_stash(repo, ref, argc, argv);
2454 }
2455
2456 int cmd_stash(int argc,
2457 const char **argv,
2458 const char *prefix,
2459 struct repository *repo)
2460 {
2461 pid_t pid = getpid();
2462 const char *index_file;
2463 struct strvec args = STRVEC_INIT;
2464 parse_opt_subcommand_fn *fn = NULL;
2465 struct option options[] = {
2466 OPT_SUBCOMMAND("apply", &fn, apply_stash),
2467 OPT_SUBCOMMAND("clear", &fn, clear_stash),
2468 OPT_SUBCOMMAND("drop", &fn, drop_stash),
2469 OPT_SUBCOMMAND("pop", &fn, pop_stash),
2470 OPT_SUBCOMMAND("branch", &fn, branch_stash),
2471 OPT_SUBCOMMAND("list", &fn, list_stash),
2472 OPT_SUBCOMMAND("show", &fn, show_stash),
2473 OPT_SUBCOMMAND("store", &fn, store_stash),
2474 OPT_SUBCOMMAND("create", &fn, create_stash),
2475 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
2476 OPT_SUBCOMMAND("export", &fn, export_stash),
2477 OPT_SUBCOMMAND("import", &fn, import_stash),
2478 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
2479 OPT_END()
2480 };
2481 const char **args_copy;
2482 int ret;
2483
2484 repo_config(the_repository, git_stash_config, NULL);
2485
2486 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
2487 PARSE_OPT_SUBCOMMAND_OPTIONAL |
2488 PARSE_OPT_KEEP_UNKNOWN_OPT |
2489 PARSE_OPT_KEEP_DASHDASH);
2490
2491 prepare_repo_settings(the_repository);
2492 the_repository->settings.command_requires_full_index = 0;
2493
2494 index_file = repo_get_index_file(the_repository);
2495 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
2496 (uintmax_t)pid);
2497
2498 if (fn) {
2499 ret = fn(argc, argv, prefix, repo);
2500
2501 /*
2502 * The subcommand implementations return 0 on success, a
2503 * negative value on failure, and STASH_APPLY_CONFLICT
2504 * when applying a stash entry resulted in conflicts.
2505 * Map failures to 128, the status die() uses, so that
2506 * exit status 1 unambiguously indicates conflicts.
2507 */
2508 if (ret < 0)
2509 return 128;
2510 return ret;
2511 } else if (!argc) {
2512 return !!push_stash_unassumed(0, NULL, prefix, repo);
2513 }
2514
2515 /* Assume 'stash push' */
2516 strvec_push(&args, "push");
2517 strvec_pushv(&args, argv);
2518
2519 /*
2520 * `push_stash()` ends up modifying the array, which causes memory
2521 * leaks if we didn't copy the array here.
2522 */
2523 DUP_ARRAY(args_copy, args.v, args.nr);
2524
2525 ret = !!push_stash(args.nr, args_copy, prefix, 1);
2526
2527 strvec_clear(&args);
2528 free(args_copy);
2529 return ret;
2530 }