]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/stash.c
7859bc0866adc10c1c83d1ec9de7b72fc2219d15
[thirdparty/git.git] / builtin / stash.c
1 #include "builtin.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hash.h"
7 #include "hex.h"
8 #include "object-name.h"
9 #include "parse-options.h"
10 #include "refs.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "unpack-trees.h"
14 #include "merge-recursive.h"
15 #include "merge-ort-wrappers.h"
16 #include "strvec.h"
17 #include "run-command.h"
18 #include "dir.h"
19 #include "entry.h"
20 #include "preload-index.h"
21 #include "read-cache.h"
22 #include "rerere.h"
23 #include "revision.h"
24 #include "setup.h"
25 #include "sparse-index.h"
26 #include "log-tree.h"
27 #include "diffcore.h"
28 #include "reflog.h"
29 #include "add-interactive.h"
30
31 #define INCLUDE_ALL_FILES 2
32
33 #define BUILTIN_STASH_LIST_USAGE \
34 N_("git stash list [<log-options>]")
35 #define BUILTIN_STASH_SHOW_USAGE \
36 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
37 #define BUILTIN_STASH_DROP_USAGE \
38 N_("git stash drop [-q | --quiet] [<stash>]")
39 #define BUILTIN_STASH_POP_USAGE \
40 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
41 #define BUILTIN_STASH_APPLY_USAGE \
42 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
43 #define BUILTIN_STASH_BRANCH_USAGE \
44 N_("git stash branch <branchname> [<stash>]")
45 #define BUILTIN_STASH_STORE_USAGE \
46 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
47 #define BUILTIN_STASH_PUSH_USAGE \
48 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
49 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
50 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
51 " [--] [<pathspec>...]]")
52 #define BUILTIN_STASH_SAVE_USAGE \
53 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
54 " [-u | --include-untracked] [-a | --all] [<message>]")
55 #define BUILTIN_STASH_CREATE_USAGE \
56 N_("git stash create [<message>]")
57 #define BUILTIN_STASH_CLEAR_USAGE \
58 "git stash clear"
59
60 static const char * const git_stash_usage[] = {
61 BUILTIN_STASH_LIST_USAGE,
62 BUILTIN_STASH_SHOW_USAGE,
63 BUILTIN_STASH_DROP_USAGE,
64 BUILTIN_STASH_POP_USAGE,
65 BUILTIN_STASH_APPLY_USAGE,
66 BUILTIN_STASH_BRANCH_USAGE,
67 BUILTIN_STASH_PUSH_USAGE,
68 BUILTIN_STASH_SAVE_USAGE,
69 BUILTIN_STASH_CLEAR_USAGE,
70 BUILTIN_STASH_CREATE_USAGE,
71 BUILTIN_STASH_STORE_USAGE,
72 NULL
73 };
74
75 static const char * const git_stash_list_usage[] = {
76 BUILTIN_STASH_LIST_USAGE,
77 NULL
78 };
79
80 static const char * const git_stash_show_usage[] = {
81 BUILTIN_STASH_SHOW_USAGE,
82 NULL
83 };
84
85 static const char * const git_stash_drop_usage[] = {
86 BUILTIN_STASH_DROP_USAGE,
87 NULL
88 };
89
90 static const char * const git_stash_pop_usage[] = {
91 BUILTIN_STASH_POP_USAGE,
92 NULL
93 };
94
95 static const char * const git_stash_apply_usage[] = {
96 BUILTIN_STASH_APPLY_USAGE,
97 NULL
98 };
99
100 static const char * const git_stash_branch_usage[] = {
101 BUILTIN_STASH_BRANCH_USAGE,
102 NULL
103 };
104
105 static const char * const git_stash_clear_usage[] = {
106 BUILTIN_STASH_CLEAR_USAGE,
107 NULL
108 };
109
110 static const char * const git_stash_store_usage[] = {
111 BUILTIN_STASH_STORE_USAGE,
112 NULL
113 };
114
115 static const char * const git_stash_push_usage[] = {
116 BUILTIN_STASH_PUSH_USAGE,
117 NULL
118 };
119
120 static const char * const git_stash_save_usage[] = {
121 BUILTIN_STASH_SAVE_USAGE,
122 NULL
123 };
124
125 static const char ref_stash[] = "refs/stash";
126 static struct strbuf stash_index_path = STRBUF_INIT;
127
128 /*
129 * w_commit is set to the commit containing the working tree
130 * b_commit is set to the base commit
131 * i_commit is set to the commit containing the index tree
132 * u_commit is set to the commit containing the untracked files tree
133 * w_tree is set to the working tree
134 * b_tree is set to the base tree
135 * i_tree is set to the index tree
136 * u_tree is set to the untracked files tree
137 */
138 struct stash_info {
139 struct object_id w_commit;
140 struct object_id b_commit;
141 struct object_id i_commit;
142 struct object_id u_commit;
143 struct object_id w_tree;
144 struct object_id b_tree;
145 struct object_id i_tree;
146 struct object_id u_tree;
147 struct strbuf revision;
148 int is_stash_ref;
149 int has_u;
150 };
151
152 #define STASH_INFO_INIT { \
153 .revision = STRBUF_INIT, \
154 }
155
156 static void free_stash_info(struct stash_info *info)
157 {
158 strbuf_release(&info->revision);
159 }
160
161 static void assert_stash_like(struct stash_info *info, const char *revision)
162 {
163 if (get_oidf(&info->b_commit, "%s^1", revision) ||
164 get_oidf(&info->w_tree, "%s:", revision) ||
165 get_oidf(&info->b_tree, "%s^1:", revision) ||
166 get_oidf(&info->i_tree, "%s^2:", revision))
167 die(_("'%s' is not a stash-like commit"), revision);
168 }
169
170 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
171 {
172 int ret;
173 char *end_of_rev;
174 char *expanded_ref;
175 const char *revision;
176 const char *commit = NULL;
177 struct object_id dummy;
178 struct strbuf symbolic = STRBUF_INIT;
179
180 if (argc > 1) {
181 int i;
182 struct strbuf refs_msg = STRBUF_INIT;
183
184 for (i = 0; i < argc; i++)
185 strbuf_addf(&refs_msg, " '%s'", argv[i]);
186
187 fprintf_ln(stderr, _("Too many revisions specified:%s"),
188 refs_msg.buf);
189 strbuf_release(&refs_msg);
190
191 return -1;
192 }
193
194 if (argc == 1)
195 commit = argv[0];
196
197 if (!commit) {
198 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash)) {
199 fprintf_ln(stderr, _("No stash entries found."));
200 return -1;
201 }
202
203 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
204 } else if (strspn(commit, "0123456789") == strlen(commit)) {
205 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
206 } else {
207 strbuf_addstr(&info->revision, commit);
208 }
209
210 revision = info->revision.buf;
211
212 if (repo_get_oid(the_repository, revision, &info->w_commit))
213 return error(_("%s is not a valid reference"), revision);
214
215 assert_stash_like(info, revision);
216
217 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
218
219 end_of_rev = strchrnul(revision, '@');
220 strbuf_add(&symbolic, revision, end_of_rev - revision);
221
222 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
223 &dummy, &expanded_ref, 0);
224 strbuf_release(&symbolic);
225 switch (ret) {
226 case 0: /* Not found, but valid ref */
227 info->is_stash_ref = 0;
228 break;
229 case 1:
230 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
231 break;
232 default: /* Invalid or ambiguous */
233 break;
234 }
235
236 free(expanded_ref);
237 return !(ret == 0 || ret == 1);
238 }
239
240 static int do_clear_stash(void)
241 {
242 struct object_id obj;
243 if (repo_get_oid(the_repository, ref_stash, &obj))
244 return 0;
245
246 return refs_delete_ref(get_main_ref_store(the_repository), NULL,
247 ref_stash, &obj, 0);
248 }
249
250 static int clear_stash(int argc, const char **argv, const char *prefix)
251 {
252 struct option options[] = {
253 OPT_END()
254 };
255
256 argc = parse_options(argc, argv, prefix, options,
257 git_stash_clear_usage,
258 PARSE_OPT_STOP_AT_NON_OPTION);
259
260 if (argc)
261 return error(_("git stash clear with arguments is "
262 "unimplemented"));
263
264 return do_clear_stash();
265 }
266
267 static int reset_tree(struct object_id *i_tree, int update, int reset)
268 {
269 int nr_trees = 1;
270 struct unpack_trees_options opts;
271 struct tree_desc t[MAX_UNPACK_TREES];
272 struct tree *tree;
273 struct lock_file lock_file = LOCK_INIT;
274
275 repo_read_index_preload(the_repository, NULL, 0);
276 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
277 return -1;
278
279 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
280
281 memset(&opts, 0, sizeof(opts));
282
283 tree = parse_tree_indirect(i_tree);
284 if (parse_tree(tree))
285 return -1;
286
287 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
288
289 opts.head_idx = 1;
290 opts.src_index = the_repository->index;
291 opts.dst_index = the_repository->index;
292 opts.merge = 1;
293 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
294 opts.update = update;
295 if (update)
296 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
297 opts.fn = oneway_merge;
298
299 if (unpack_trees(nr_trees, t, &opts))
300 return -1;
301
302 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
303 return error(_("unable to write new index file"));
304
305 return 0;
306 }
307
308 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
309 {
310 struct child_process cp = CHILD_PROCESS_INIT;
311 const char *w_commit_hex = oid_to_hex(w_commit);
312
313 /*
314 * Diff-tree would not be very hard to replace with a native function,
315 * however it should be done together with apply_cached.
316 */
317 cp.git_cmd = 1;
318 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
319 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
320
321 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
322 }
323
324 static int apply_cached(struct strbuf *out)
325 {
326 struct child_process cp = CHILD_PROCESS_INIT;
327
328 /*
329 * Apply currently only reads either from stdin or a file, thus
330 * apply_all_patches would have to be updated to optionally take a
331 * buffer.
332 */
333 cp.git_cmd = 1;
334 strvec_pushl(&cp.args, "apply", "--cached", NULL);
335 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
336 }
337
338 static int reset_head(void)
339 {
340 struct child_process cp = CHILD_PROCESS_INIT;
341
342 /*
343 * Reset is overall quite simple, however there is no current public
344 * API for resetting.
345 */
346 cp.git_cmd = 1;
347 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
348
349 return run_command(&cp);
350 }
351
352 static int is_path_a_directory(const char *path)
353 {
354 /*
355 * This function differs from abspath.c:is_directory() in that
356 * here we use lstat() instead of stat(); we do not want to
357 * follow symbolic links here.
358 */
359 struct stat st;
360 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
361 }
362
363 static void add_diff_to_buf(struct diff_queue_struct *q,
364 struct diff_options *options UNUSED,
365 void *data)
366 {
367 int i;
368
369 for (i = 0; i < q->nr; i++) {
370 if (is_path_a_directory(q->queue[i]->one->path))
371 continue;
372
373 strbuf_addstr(data, q->queue[i]->one->path);
374
375 /* NUL-terminate: will be fed to update-index -z */
376 strbuf_addch(data, '\0');
377 }
378 }
379
380 static int restore_untracked(struct object_id *u_tree)
381 {
382 int res;
383 struct child_process cp = CHILD_PROCESS_INIT;
384
385 /*
386 * We need to run restore files from a given index, but without
387 * affecting the current index, so we use GIT_INDEX_FILE with
388 * run_command to fork processes that will not interfere.
389 */
390 cp.git_cmd = 1;
391 strvec_push(&cp.args, "read-tree");
392 strvec_push(&cp.args, oid_to_hex(u_tree));
393 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
394 stash_index_path.buf);
395 if (run_command(&cp)) {
396 remove_path(stash_index_path.buf);
397 return -1;
398 }
399
400 child_process_init(&cp);
401 cp.git_cmd = 1;
402 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
403 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
404 stash_index_path.buf);
405
406 res = run_command(&cp);
407 remove_path(stash_index_path.buf);
408 return res;
409 }
410
411 static void unstage_changes_unless_new(struct object_id *orig_tree)
412 {
413 /*
414 * When we enter this function, there has been a clean merge of
415 * relevant trees, and the merge logic always stages whatever merges
416 * cleanly. We want to unstage those changes, unless it corresponds
417 * to a file that didn't exist as of orig_tree.
418 *
419 * However, if any SKIP_WORKTREE path is modified relative to
420 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
421 * it to the worktree before unstaging.
422 */
423
424 struct checkout state = CHECKOUT_INIT;
425 struct diff_options diff_opts;
426 struct lock_file lock = LOCK_INIT;
427 int i;
428
429 /* If any entries have skip_worktree set, we'll have to check 'em out */
430 state.force = 1;
431 state.quiet = 1;
432 state.refresh_cache = 1;
433 state.istate = the_repository->index;
434
435 /*
436 * Step 1: get a difference between orig_tree (which corresponding
437 * to the index before a merge was run) and the current index
438 * (reflecting the changes brought in by the merge).
439 */
440 repo_diff_setup(the_repository, &diff_opts);
441 diff_opts.flags.recursive = 1;
442 diff_opts.detect_rename = 0;
443 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
444 diff_setup_done(&diff_opts);
445
446 do_diff_cache(orig_tree, &diff_opts);
447 diffcore_std(&diff_opts);
448
449 /* Iterate over the paths that changed due to the merge... */
450 for (i = 0; i < diff_queued_diff.nr; i++) {
451 struct diff_filepair *p;
452 struct cache_entry *ce;
453 int pos;
454
455 /* Look up the path's position in the current index. */
456 p = diff_queued_diff.queue[i];
457 pos = index_name_pos(the_repository->index, p->two->path,
458 strlen(p->two->path));
459
460 /*
461 * Step 2: Place changes in the working tree
462 *
463 * Stash is about restoring changes *to the working tree*.
464 * So if the merge successfully got a new version of some
465 * path, but left it out of the working tree, then clear the
466 * SKIP_WORKTREE bit and write it to the working tree.
467 */
468 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
469 struct stat st;
470
471 ce = the_repository->index->cache[pos];
472 if (!lstat(ce->name, &st)) {
473 /* Conflicting path present; relocate it */
474 struct strbuf new_path = STRBUF_INIT;
475 int fd;
476
477 strbuf_addf(&new_path,
478 "%s.stash.XXXXXX", ce->name);
479 fd = xmkstemp(new_path.buf);
480 close(fd);
481 printf(_("WARNING: Untracked file in way of "
482 "tracked file! Renaming\n "
483 " %s -> %s\n"
484 " to make room.\n"),
485 ce->name, new_path.buf);
486 if (rename(ce->name, new_path.buf))
487 die("Failed to move %s to %s\n",
488 ce->name, new_path.buf);
489 strbuf_release(&new_path);
490 }
491 checkout_entry(ce, &state, NULL, NULL);
492 ce->ce_flags &= ~CE_SKIP_WORKTREE;
493 }
494
495 /*
496 * Step 3: "unstage" changes, as long as they are still tracked
497 */
498 if (p->one->oid_valid) {
499 /*
500 * Path existed in orig_tree; restore index entry
501 * from that tree in order to "unstage" the changes.
502 */
503 int option = ADD_CACHE_OK_TO_REPLACE;
504 if (pos < 0)
505 option = ADD_CACHE_OK_TO_ADD;
506
507 ce = make_cache_entry(the_repository->index,
508 p->one->mode,
509 &p->one->oid,
510 p->one->path,
511 0, 0);
512 add_index_entry(the_repository->index, ce, option);
513 }
514 }
515 diff_flush(&diff_opts);
516
517 /*
518 * Step 4: write the new index to disk
519 */
520 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
521 if (write_locked_index(the_repository->index, &lock,
522 COMMIT_LOCK | SKIP_IF_UNCHANGED))
523 die(_("could not write index"));
524 }
525
526 static int do_apply_stash(const char *prefix, struct stash_info *info,
527 int index, int quiet)
528 {
529 int clean, ret;
530 int has_index = index;
531 struct merge_options o;
532 struct object_id c_tree;
533 struct object_id index_tree;
534 struct tree *head, *merge, *merge_base;
535 struct lock_file lock = LOCK_INIT;
536
537 repo_read_index_preload(the_repository, NULL, 0);
538 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
539 NULL, NULL, NULL))
540 return error(_("could not write index"));
541
542 if (write_index_as_tree(&c_tree, the_repository->index, get_index_file(), 0,
543 NULL))
544 return error(_("cannot apply a stash in the middle of a merge"));
545
546 if (index) {
547 if (oideq(&info->b_tree, &info->i_tree) ||
548 oideq(&c_tree, &info->i_tree)) {
549 has_index = 0;
550 } else {
551 struct strbuf out = STRBUF_INIT;
552
553 if (diff_tree_binary(&out, &info->w_commit)) {
554 strbuf_release(&out);
555 return error(_("could not generate diff %s^!."),
556 oid_to_hex(&info->w_commit));
557 }
558
559 ret = apply_cached(&out);
560 strbuf_release(&out);
561 if (ret)
562 return error(_("conflicts in index. "
563 "Try without --index."));
564
565 discard_index(the_repository->index);
566 repo_read_index(the_repository);
567 if (write_index_as_tree(&index_tree, the_repository->index,
568 get_index_file(), 0, NULL))
569 return error(_("could not save index tree"));
570
571 reset_head();
572 discard_index(the_repository->index);
573 repo_read_index(the_repository);
574 }
575 }
576
577 init_merge_options(&o, the_repository);
578
579 o.branch1 = "Updated upstream";
580 o.branch2 = "Stashed changes";
581 o.ancestor = "Stash base";
582
583 if (oideq(&info->b_tree, &c_tree))
584 o.branch1 = "Version stash was based on";
585
586 if (quiet)
587 o.verbosity = 0;
588
589 if (o.verbosity >= 3)
590 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
591
592 head = lookup_tree(o.repo, &c_tree);
593 merge = lookup_tree(o.repo, &info->w_tree);
594 merge_base = lookup_tree(o.repo, &info->b_tree);
595
596 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
597 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
598
599 /*
600 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
601 * merge was clean, and nonzero if the merge was unclean or encountered
602 * an error.
603 */
604 ret = clean >= 0 ? !clean : clean;
605
606 if (ret < 0)
607 rollback_lock_file(&lock);
608 else if (write_locked_index(o.repo->index, &lock,
609 COMMIT_LOCK | SKIP_IF_UNCHANGED))
610 ret = error(_("could not write index"));
611
612 if (ret) {
613 repo_rerere(the_repository, 0);
614
615 if (index)
616 fprintf_ln(stderr, _("Index was not unstashed."));
617
618 goto restore_untracked;
619 }
620
621 if (has_index) {
622 if (reset_tree(&index_tree, 0, 0))
623 ret = -1;
624 } else {
625 unstage_changes_unless_new(&c_tree);
626 }
627
628 restore_untracked:
629 if (info->has_u && restore_untracked(&info->u_tree))
630 ret = error(_("could not restore untracked files from stash"));
631
632 if (!quiet) {
633 struct child_process cp = CHILD_PROCESS_INIT;
634
635 /*
636 * Status is quite simple and could be replaced with calls to
637 * wt_status in the future, but it adds complexities which may
638 * require more tests.
639 */
640 cp.git_cmd = 1;
641 cp.dir = prefix;
642 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
643 absolute_path(get_git_work_tree()));
644 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
645 absolute_path(get_git_dir()));
646 strvec_push(&cp.args, "status");
647 run_command(&cp);
648 }
649
650 return ret;
651 }
652
653 static int apply_stash(int argc, const char **argv, const char *prefix)
654 {
655 int ret = -1;
656 int quiet = 0;
657 int index = 0;
658 struct stash_info info = STASH_INFO_INIT;
659 struct option options[] = {
660 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
661 OPT_BOOL(0, "index", &index,
662 N_("attempt to recreate the index")),
663 OPT_END()
664 };
665
666 argc = parse_options(argc, argv, prefix, options,
667 git_stash_apply_usage, 0);
668
669 if (get_stash_info(&info, argc, argv))
670 goto cleanup;
671
672 ret = do_apply_stash(prefix, &info, index, quiet);
673 cleanup:
674 free_stash_info(&info);
675 return ret;
676 }
677
678 static int reject_reflog_ent(struct object_id *ooid UNUSED,
679 struct object_id *noid UNUSED,
680 const char *email UNUSED,
681 timestamp_t timestamp UNUSED,
682 int tz UNUSED, const char *message UNUSED,
683 void *cb_data UNUSED)
684 {
685 return 1;
686 }
687
688 static int reflog_is_empty(const char *refname)
689 {
690 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository),
691 refname, reject_reflog_ent, NULL);
692 }
693
694 static int do_drop_stash(struct stash_info *info, int quiet)
695 {
696 if (!reflog_delete(info->revision.buf,
697 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
698 0)) {
699 if (!quiet)
700 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
701 oid_to_hex(&info->w_commit));
702 } else {
703 return error(_("%s: Could not drop stash entry"),
704 info->revision.buf);
705 }
706
707 if (reflog_is_empty(ref_stash))
708 do_clear_stash();
709
710 return 0;
711 }
712
713 static int get_stash_info_assert(struct stash_info *info, int argc,
714 const char **argv)
715 {
716 int ret = get_stash_info(info, argc, argv);
717
718 if (ret < 0)
719 return ret;
720
721 if (!info->is_stash_ref)
722 return error(_("'%s' is not a stash reference"), info->revision.buf);
723
724 return 0;
725 }
726
727 static int drop_stash(int argc, const char **argv, const char *prefix)
728 {
729 int ret = -1;
730 int quiet = 0;
731 struct stash_info info = STASH_INFO_INIT;
732 struct option options[] = {
733 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
734 OPT_END()
735 };
736
737 argc = parse_options(argc, argv, prefix, options,
738 git_stash_drop_usage, 0);
739
740 if (get_stash_info_assert(&info, argc, argv))
741 goto cleanup;
742
743 ret = do_drop_stash(&info, quiet);
744 cleanup:
745 free_stash_info(&info);
746 return ret;
747 }
748
749 static int pop_stash(int argc, const char **argv, const char *prefix)
750 {
751 int ret = -1;
752 int index = 0;
753 int quiet = 0;
754 struct stash_info info = STASH_INFO_INIT;
755 struct option options[] = {
756 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
757 OPT_BOOL(0, "index", &index,
758 N_("attempt to recreate the index")),
759 OPT_END()
760 };
761
762 argc = parse_options(argc, argv, prefix, options,
763 git_stash_pop_usage, 0);
764
765 if (get_stash_info_assert(&info, argc, argv))
766 goto cleanup;
767
768 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
769 printf_ln(_("The stash entry is kept in case "
770 "you need it again."));
771 else
772 ret = do_drop_stash(&info, quiet);
773
774 cleanup:
775 free_stash_info(&info);
776 return ret;
777 }
778
779 static int branch_stash(int argc, const char **argv, const char *prefix)
780 {
781 int ret = -1;
782 const char *branch = NULL;
783 struct stash_info info = STASH_INFO_INIT;
784 struct child_process cp = CHILD_PROCESS_INIT;
785 struct option options[] = {
786 OPT_END()
787 };
788
789 argc = parse_options(argc, argv, prefix, options,
790 git_stash_branch_usage, 0);
791
792 if (!argc) {
793 fprintf_ln(stderr, _("No branch name specified"));
794 return -1;
795 }
796
797 branch = argv[0];
798
799 if (get_stash_info(&info, argc - 1, argv + 1))
800 goto cleanup;
801
802 cp.git_cmd = 1;
803 strvec_pushl(&cp.args, "checkout", "-b", NULL);
804 strvec_push(&cp.args, branch);
805 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
806 ret = run_command(&cp);
807 if (!ret)
808 ret = do_apply_stash(prefix, &info, 1, 0);
809 if (!ret && info.is_stash_ref)
810 ret = do_drop_stash(&info, 0);
811
812 cleanup:
813 free_stash_info(&info);
814 return ret;
815 }
816
817 static int list_stash(int argc, const char **argv, const char *prefix)
818 {
819 struct child_process cp = CHILD_PROCESS_INIT;
820 struct option options[] = {
821 OPT_END()
822 };
823
824 argc = parse_options(argc, argv, prefix, options,
825 git_stash_list_usage,
826 PARSE_OPT_KEEP_UNKNOWN_OPT);
827
828 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash))
829 return 0;
830
831 cp.git_cmd = 1;
832 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
833 "--first-parent", NULL);
834 strvec_pushv(&cp.args, argv);
835 strvec_push(&cp.args, ref_stash);
836 strvec_push(&cp.args, "--");
837 return run_command(&cp);
838 }
839
840 static int show_stat = 1;
841 static int show_patch;
842 static int show_include_untracked;
843
844 static int git_stash_config(const char *var, const char *value,
845 const struct config_context *ctx, void *cb)
846 {
847 if (!strcmp(var, "stash.showstat")) {
848 show_stat = git_config_bool(var, value);
849 return 0;
850 }
851 if (!strcmp(var, "stash.showpatch")) {
852 show_patch = git_config_bool(var, value);
853 return 0;
854 }
855 if (!strcmp(var, "stash.showincludeuntracked")) {
856 show_include_untracked = git_config_bool(var, value);
857 return 0;
858 }
859 return git_diff_basic_config(var, value, ctx, cb);
860 }
861
862 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
863 {
864 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
865 struct tree *tree[ARRAY_SIZE(oid)];
866 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
867 struct unpack_trees_options unpack_tree_opt = { 0 };
868 int i;
869
870 for (i = 0; i < ARRAY_SIZE(oid); i++) {
871 tree[i] = parse_tree_indirect(oid[i]);
872 if (parse_tree(tree[i]) < 0)
873 die(_("failed to parse tree"));
874 init_tree_desc(&tree_desc[i], &tree[i]->object.oid,
875 tree[i]->buffer, tree[i]->size);
876 }
877
878 unpack_tree_opt.head_idx = -1;
879 unpack_tree_opt.src_index = the_repository->index;
880 unpack_tree_opt.dst_index = the_repository->index;
881 unpack_tree_opt.merge = 1;
882 unpack_tree_opt.fn = stash_worktree_untracked_merge;
883
884 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
885 die(_("failed to unpack trees"));
886
887 do_diff_cache(&info->b_commit, diff_opt);
888 }
889
890 static int show_stash(int argc, const char **argv, const char *prefix)
891 {
892 int i;
893 int ret = -1;
894 struct stash_info info = STASH_INFO_INIT;
895 struct rev_info rev;
896 struct strvec stash_args = STRVEC_INIT;
897 struct strvec revision_args = STRVEC_INIT;
898 enum {
899 UNTRACKED_NONE,
900 UNTRACKED_INCLUDE,
901 UNTRACKED_ONLY
902 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
903 struct option options[] = {
904 OPT_SET_INT('u', "include-untracked", &show_untracked,
905 N_("include untracked files in the stash"),
906 UNTRACKED_INCLUDE),
907 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
908 N_("only show untracked files in the stash"),
909 UNTRACKED_ONLY, PARSE_OPT_NONEG),
910 OPT_END()
911 };
912 int do_usage = 0;
913
914 init_diff_ui_defaults();
915 git_config(git_diff_ui_config, NULL);
916 repo_init_revisions(the_repository, &rev, prefix);
917
918 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
919 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
920 PARSE_OPT_KEEP_DASHDASH);
921
922 strvec_push(&revision_args, argv[0]);
923 for (i = 1; i < argc; i++) {
924 if (argv[i][0] != '-')
925 strvec_push(&stash_args, argv[i]);
926 else
927 strvec_push(&revision_args, argv[i]);
928 }
929
930 if (get_stash_info(&info, stash_args.nr, stash_args.v))
931 goto cleanup;
932
933 /*
934 * The config settings are applied only if there are not passed
935 * any options.
936 */
937 if (revision_args.nr == 1) {
938 if (show_stat)
939 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
940
941 if (show_patch)
942 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
943
944 if (!show_stat && !show_patch) {
945 ret = 0;
946 goto cleanup;
947 }
948 }
949
950 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
951 if (argc > 1)
952 goto usage;
953 if (!rev.diffopt.output_format) {
954 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
955 diff_setup_done(&rev.diffopt);
956 }
957
958 rev.diffopt.flags.recursive = 1;
959 setup_diff_pager(&rev.diffopt);
960 switch (show_untracked) {
961 case UNTRACKED_NONE:
962 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
963 break;
964 case UNTRACKED_ONLY:
965 if (info.has_u)
966 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
967 break;
968 case UNTRACKED_INCLUDE:
969 if (info.has_u)
970 diff_include_untracked(&info, &rev.diffopt);
971 else
972 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
973 break;
974 }
975 log_tree_diff_flush(&rev);
976
977 ret = diff_result_code(&rev.diffopt);
978 cleanup:
979 strvec_clear(&stash_args);
980 free_stash_info(&info);
981 release_revisions(&rev);
982 if (do_usage)
983 usage_with_options(git_stash_show_usage, options);
984 return ret;
985 usage:
986 do_usage = 1;
987 goto cleanup;
988 }
989
990 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
991 int quiet)
992 {
993 struct stash_info info;
994 char revision[GIT_MAX_HEXSZ];
995
996 oid_to_hex_r(revision, w_commit);
997 assert_stash_like(&info, revision);
998
999 if (!stash_msg)
1000 stash_msg = "Created via \"git stash store\".";
1001
1002 if (refs_update_ref(get_main_ref_store(the_repository), stash_msg, ref_stash, w_commit, NULL,
1003 REF_FORCE_CREATE_REFLOG,
1004 quiet ? UPDATE_REFS_QUIET_ON_ERR :
1005 UPDATE_REFS_MSG_ON_ERR)) {
1006 if (!quiet) {
1007 fprintf_ln(stderr, _("Cannot update %s with %s"),
1008 ref_stash, oid_to_hex(w_commit));
1009 }
1010 return -1;
1011 }
1012
1013 return 0;
1014 }
1015
1016 static int store_stash(int argc, const char **argv, const char *prefix)
1017 {
1018 int quiet = 0;
1019 const char *stash_msg = NULL;
1020 struct object_id obj;
1021 struct object_context dummy;
1022 struct option options[] = {
1023 OPT__QUIET(&quiet, N_("be quiet")),
1024 OPT_STRING('m', "message", &stash_msg, "message",
1025 N_("stash message")),
1026 OPT_END()
1027 };
1028
1029 argc = parse_options(argc, argv, prefix, options,
1030 git_stash_store_usage,
1031 PARSE_OPT_KEEP_UNKNOWN_OPT);
1032
1033 if (argc != 1) {
1034 if (!quiet)
1035 fprintf_ln(stderr, _("\"git stash store\" requires one "
1036 "<commit> argument"));
1037 return -1;
1038 }
1039
1040 if (get_oid_with_context(the_repository,
1041 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1042 &dummy)) {
1043 if (!quiet)
1044 fprintf_ln(stderr, _("Cannot update %s with %s"),
1045 ref_stash, argv[0]);
1046 return -1;
1047 }
1048
1049 return do_store_stash(&obj, stash_msg, quiet);
1050 }
1051
1052 static void add_pathspecs(struct strvec *args,
1053 const struct pathspec *ps) {
1054 int i;
1055
1056 for (i = 0; i < ps->nr; i++)
1057 strvec_push(args, ps->items[i].original);
1058 }
1059
1060 /*
1061 * `untracked_files` will be filled with the names of untracked files.
1062 * The return value is:
1063 *
1064 * = 0 if there are not any untracked files
1065 * > 0 if there are untracked files
1066 */
1067 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1068 struct strbuf *untracked_files)
1069 {
1070 int i;
1071 int found = 0;
1072 struct dir_struct dir = DIR_INIT;
1073
1074 if (include_untracked != INCLUDE_ALL_FILES)
1075 setup_standard_excludes(&dir);
1076
1077 fill_directory(&dir, the_repository->index, ps);
1078 for (i = 0; i < dir.nr; i++) {
1079 struct dir_entry *ent = dir.entries[i];
1080 found++;
1081 strbuf_addstr(untracked_files, ent->name);
1082 /* NUL-terminate: will be fed to update-index -z */
1083 strbuf_addch(untracked_files, '\0');
1084 }
1085
1086 dir_clear(&dir);
1087 return found;
1088 }
1089
1090 /*
1091 * The return value of `check_changes_tracked_files()` can be:
1092 *
1093 * < 0 if there was an error
1094 * = 0 if there are no changes.
1095 * > 0 if there are changes.
1096 */
1097 static int check_changes_tracked_files(const struct pathspec *ps)
1098 {
1099 struct rev_info rev;
1100 struct object_id dummy;
1101 int ret = 0;
1102
1103 /* No initial commit. */
1104 if (repo_get_oid(the_repository, "HEAD", &dummy))
1105 return -1;
1106
1107 if (repo_read_index(the_repository) < 0)
1108 return -1;
1109
1110 repo_init_revisions(the_repository, &rev, NULL);
1111 copy_pathspec(&rev.prune_data, ps);
1112
1113 rev.diffopt.flags.quick = 1;
1114 rev.diffopt.flags.ignore_submodules = 1;
1115 rev.abbrev = 0;
1116
1117 add_head_to_pending(&rev);
1118 diff_setup_done(&rev.diffopt);
1119
1120 run_diff_index(&rev, DIFF_INDEX_CACHED);
1121 if (diff_result_code(&rev.diffopt)) {
1122 ret = 1;
1123 goto done;
1124 }
1125
1126 run_diff_files(&rev, 0);
1127 if (diff_result_code(&rev.diffopt)) {
1128 ret = 1;
1129 goto done;
1130 }
1131
1132 done:
1133 release_revisions(&rev);
1134 return ret;
1135 }
1136
1137 /*
1138 * The function will fill `untracked_files` with the names of untracked files
1139 * It will return 1 if there were any changes and 0 if there were not.
1140 */
1141 static int check_changes(const struct pathspec *ps, int include_untracked,
1142 struct strbuf *untracked_files)
1143 {
1144 int ret = 0;
1145 if (check_changes_tracked_files(ps))
1146 ret = 1;
1147
1148 if (include_untracked && get_untracked_files(ps, include_untracked,
1149 untracked_files))
1150 ret = 1;
1151
1152 return ret;
1153 }
1154
1155 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1156 struct strbuf files)
1157 {
1158 int ret = 0;
1159 struct strbuf untracked_msg = STRBUF_INIT;
1160 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1161 struct index_state istate = INDEX_STATE_INIT(the_repository);
1162
1163 cp_upd_index.git_cmd = 1;
1164 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1165 "--remove", "--stdin", NULL);
1166 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1167 stash_index_path.buf);
1168
1169 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1170 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1171 NULL, 0)) {
1172 ret = -1;
1173 goto done;
1174 }
1175
1176 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1177 NULL)) {
1178 ret = -1;
1179 goto done;
1180 }
1181
1182 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1183 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1184 ret = -1;
1185 goto done;
1186 }
1187
1188 done:
1189 release_index(&istate);
1190 strbuf_release(&untracked_msg);
1191 remove_path(stash_index_path.buf);
1192 return ret;
1193 }
1194
1195 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1196 int quiet)
1197 {
1198 int ret = 0;
1199 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1200 struct index_state istate = INDEX_STATE_INIT(the_repository);
1201
1202 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1203 0, NULL)) {
1204 ret = -1;
1205 goto done;
1206 }
1207
1208 cp_diff_tree.git_cmd = 1;
1209 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "--binary",
1210 "-U1", "HEAD", oid_to_hex(&info->w_tree), "--", NULL);
1211 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1212 ret = -1;
1213 goto done;
1214 }
1215
1216 if (!out_patch->len) {
1217 if (!quiet)
1218 fprintf_ln(stderr, _("No staged changes"));
1219 ret = 1;
1220 }
1221
1222 done:
1223 release_index(&istate);
1224 return ret;
1225 }
1226
1227 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1228 struct strbuf *out_patch, int quiet)
1229 {
1230 int ret = 0;
1231 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1232 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1233 struct index_state istate = INDEX_STATE_INIT(the_repository);
1234 char *old_index_env = NULL, *old_repo_index_file;
1235
1236 remove_path(stash_index_path.buf);
1237
1238 cp_read_tree.git_cmd = 1;
1239 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1240 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1241 stash_index_path.buf);
1242 if (run_command(&cp_read_tree)) {
1243 ret = -1;
1244 goto done;
1245 }
1246
1247 /* Find out what the user wants. */
1248 old_repo_index_file = the_repository->index_file;
1249 the_repository->index_file = stash_index_path.buf;
1250 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1251 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1252
1253 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1254
1255 the_repository->index_file = old_repo_index_file;
1256 if (old_index_env && *old_index_env)
1257 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1258 else
1259 unsetenv(INDEX_ENVIRONMENT);
1260 FREE_AND_NULL(old_index_env);
1261
1262 /* State of the working tree. */
1263 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1264 NULL)) {
1265 ret = -1;
1266 goto done;
1267 }
1268
1269 cp_diff_tree.git_cmd = 1;
1270 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1271 oid_to_hex(&info->w_tree), "--", NULL);
1272 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1273 ret = -1;
1274 goto done;
1275 }
1276
1277 if (!out_patch->len) {
1278 if (!quiet)
1279 fprintf_ln(stderr, _("No changes selected"));
1280 ret = 1;
1281 }
1282
1283 done:
1284 release_index(&istate);
1285 remove_path(stash_index_path.buf);
1286 return ret;
1287 }
1288
1289 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1290 {
1291 int ret = 0;
1292 struct rev_info rev;
1293 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1294 struct strbuf diff_output = STRBUF_INIT;
1295 struct index_state istate = INDEX_STATE_INIT(the_repository);
1296
1297 repo_init_revisions(the_repository, &rev, NULL);
1298 copy_pathspec(&rev.prune_data, ps);
1299
1300 set_alternate_index_output(stash_index_path.buf);
1301 if (reset_tree(&info->i_tree, 0, 0)) {
1302 ret = -1;
1303 goto done;
1304 }
1305 set_alternate_index_output(NULL);
1306
1307 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1308 rev.diffopt.format_callback = add_diff_to_buf;
1309 rev.diffopt.format_callback_data = &diff_output;
1310
1311 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1312 ret = -1;
1313 goto done;
1314 }
1315
1316 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1317 "");
1318 run_diff_index(&rev, 0);
1319
1320 cp_upd_index.git_cmd = 1;
1321 strvec_pushl(&cp_upd_index.args, "update-index",
1322 "--ignore-skip-worktree-entries",
1323 "-z", "--add", "--remove", "--stdin", NULL);
1324 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1325 stash_index_path.buf);
1326
1327 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1328 NULL, 0, NULL, 0)) {
1329 ret = -1;
1330 goto done;
1331 }
1332
1333 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1334 NULL)) {
1335 ret = -1;
1336 goto done;
1337 }
1338
1339 done:
1340 release_index(&istate);
1341 release_revisions(&rev);
1342 strbuf_release(&diff_output);
1343 remove_path(stash_index_path.buf);
1344 return ret;
1345 }
1346
1347 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1348 int include_untracked, int patch_mode, int only_staged,
1349 struct stash_info *info, struct strbuf *patch,
1350 int quiet)
1351 {
1352 int ret = 0;
1353 int flags = 0;
1354 int untracked_commit_option = 0;
1355 const char *head_short_sha1 = NULL;
1356 const char *branch_ref = NULL;
1357 const char *branch_name = "(no branch)";
1358 struct commit *head_commit = NULL;
1359 struct commit_list *parents = NULL;
1360 struct strbuf msg = STRBUF_INIT;
1361 struct strbuf commit_tree_label = STRBUF_INIT;
1362 struct strbuf untracked_files = STRBUF_INIT;
1363
1364 prepare_fallback_ident("git stash", "git@stash");
1365
1366 repo_read_index_preload(the_repository, NULL, 0);
1367 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1368 NULL, NULL, NULL) < 0) {
1369 ret = error(_("could not write index"));
1370 goto done;
1371 }
1372
1373 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1374 if (!quiet)
1375 fprintf_ln(stderr, _("You do not have "
1376 "the initial commit yet"));
1377 ret = -1;
1378 goto done;
1379 } else {
1380 head_commit = lookup_commit(the_repository, &info->b_commit);
1381 }
1382
1383 if (!check_changes(ps, include_untracked, &untracked_files)) {
1384 ret = 1;
1385 goto done;
1386 }
1387
1388 branch_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1389 "HEAD", 0, NULL, &flags);
1390 if (flags & REF_ISSYMREF)
1391 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1392 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1393 &head_commit->object.oid,
1394 DEFAULT_ABBREV);
1395 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1396 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1397
1398 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1399 commit_list_insert(head_commit, &parents);
1400 if (write_index_as_tree(&info->i_tree, the_repository->index, get_index_file(), 0,
1401 NULL) ||
1402 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1403 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1404 if (!quiet)
1405 fprintf_ln(stderr, _("Cannot save the current "
1406 "index state"));
1407 ret = -1;
1408 goto done;
1409 }
1410
1411 if (include_untracked) {
1412 if (save_untracked_files(info, &msg, untracked_files)) {
1413 if (!quiet)
1414 fprintf_ln(stderr, _("Cannot save "
1415 "the untracked files"));
1416 ret = -1;
1417 goto done;
1418 }
1419 untracked_commit_option = 1;
1420 }
1421 if (patch_mode) {
1422 ret = stash_patch(info, ps, patch, quiet);
1423 if (ret < 0) {
1424 if (!quiet)
1425 fprintf_ln(stderr, _("Cannot save the current "
1426 "worktree state"));
1427 goto done;
1428 } else if (ret > 0) {
1429 goto done;
1430 }
1431 } else if (only_staged) {
1432 ret = stash_staged(info, patch, quiet);
1433 if (ret < 0) {
1434 if (!quiet)
1435 fprintf_ln(stderr, _("Cannot save the current "
1436 "staged state"));
1437 goto done;
1438 } else if (ret > 0) {
1439 goto done;
1440 }
1441 } else {
1442 if (stash_working_tree(info, ps)) {
1443 if (!quiet)
1444 fprintf_ln(stderr, _("Cannot save the current "
1445 "worktree state"));
1446 ret = -1;
1447 goto done;
1448 }
1449 }
1450
1451 if (!stash_msg_buf->len)
1452 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1453 else
1454 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1455
1456 /*
1457 * `parents` will be empty after calling `commit_tree()`, so there is
1458 * no need to call `free_commit_list()`
1459 */
1460 parents = NULL;
1461 if (untracked_commit_option)
1462 commit_list_insert(lookup_commit(the_repository,
1463 &info->u_commit),
1464 &parents);
1465 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1466 &parents);
1467 commit_list_insert(head_commit, &parents);
1468
1469 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1470 parents, &info->w_commit, NULL, NULL)) {
1471 if (!quiet)
1472 fprintf_ln(stderr, _("Cannot record "
1473 "working tree state"));
1474 ret = -1;
1475 goto done;
1476 }
1477
1478 done:
1479 strbuf_release(&commit_tree_label);
1480 strbuf_release(&msg);
1481 strbuf_release(&untracked_files);
1482 return ret;
1483 }
1484
1485 static int create_stash(int argc, const char **argv, const char *prefix UNUSED)
1486 {
1487 int ret;
1488 struct strbuf stash_msg_buf = STRBUF_INIT;
1489 struct stash_info info = STASH_INFO_INIT;
1490 struct pathspec ps;
1491
1492 /* Starting with argv[1], since argv[0] is "create" */
1493 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1494
1495 memset(&ps, 0, sizeof(ps));
1496 if (!check_changes_tracked_files(&ps))
1497 return 0;
1498
1499 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1500 NULL, 0);
1501 if (!ret)
1502 printf_ln("%s", oid_to_hex(&info.w_commit));
1503
1504 free_stash_info(&info);
1505 strbuf_release(&stash_msg_buf);
1506 return ret;
1507 }
1508
1509 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1510 int keep_index, int patch_mode, int include_untracked, int only_staged)
1511 {
1512 int ret = 0;
1513 struct stash_info info = STASH_INFO_INIT;
1514 struct strbuf patch = STRBUF_INIT;
1515 struct strbuf stash_msg_buf = STRBUF_INIT;
1516 struct strbuf untracked_files = STRBUF_INIT;
1517
1518 if (patch_mode && keep_index == -1)
1519 keep_index = 1;
1520
1521 if (patch_mode && include_untracked) {
1522 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1523 " or --all at the same time"));
1524 ret = -1;
1525 goto done;
1526 }
1527
1528 /* --patch overrides --staged */
1529 if (patch_mode)
1530 only_staged = 0;
1531
1532 if (only_staged && include_untracked) {
1533 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1534 " or --all at the same time"));
1535 ret = -1;
1536 goto done;
1537 }
1538
1539 repo_read_index_preload(the_repository, NULL, 0);
1540 if (!include_untracked && ps->nr) {
1541 int i;
1542 char *ps_matched = xcalloc(ps->nr, 1);
1543
1544 /* TODO: audit for interaction with sparse-index. */
1545 ensure_full_index(the_repository->index);
1546 for (i = 0; i < the_repository->index->cache_nr; i++)
1547 ce_path_match(the_repository->index, the_repository->index->cache[i], ps,
1548 ps_matched);
1549
1550 if (report_path_error(ps_matched, ps)) {
1551 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1552 ret = -1;
1553 free(ps_matched);
1554 goto done;
1555 }
1556 free(ps_matched);
1557 }
1558
1559 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1560 NULL, NULL, NULL)) {
1561 ret = error(_("could not write index"));
1562 goto done;
1563 }
1564
1565 if (!check_changes(ps, include_untracked, &untracked_files)) {
1566 if (!quiet)
1567 printf_ln(_("No local changes to save"));
1568 goto done;
1569 }
1570
1571 if (!refs_reflog_exists(get_main_ref_store(the_repository), ref_stash) && do_clear_stash()) {
1572 ret = -1;
1573 if (!quiet)
1574 fprintf_ln(stderr, _("Cannot initialize stash"));
1575 goto done;
1576 }
1577
1578 if (stash_msg)
1579 strbuf_addstr(&stash_msg_buf, stash_msg);
1580 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1581 &info, &patch, quiet)) {
1582 ret = -1;
1583 goto done;
1584 }
1585
1586 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1587 ret = -1;
1588 if (!quiet)
1589 fprintf_ln(stderr, _("Cannot save the current status"));
1590 goto done;
1591 }
1592
1593 if (!quiet)
1594 printf_ln(_("Saved working directory and index state %s"),
1595 stash_msg_buf.buf);
1596
1597 if (!(patch_mode || only_staged)) {
1598 if (include_untracked && !ps->nr) {
1599 struct child_process cp = CHILD_PROCESS_INIT;
1600
1601 cp.git_cmd = 1;
1602 if (startup_info->original_cwd) {
1603 cp.dir = startup_info->original_cwd;
1604 strvec_pushf(&cp.env, "%s=%s",
1605 GIT_WORK_TREE_ENVIRONMENT,
1606 the_repository->worktree);
1607 }
1608 strvec_pushl(&cp.args, "clean", "--force",
1609 "--quiet", "-d", ":/", NULL);
1610 if (include_untracked == INCLUDE_ALL_FILES)
1611 strvec_push(&cp.args, "-x");
1612 if (run_command(&cp)) {
1613 ret = -1;
1614 goto done;
1615 }
1616 }
1617 discard_index(the_repository->index);
1618 if (ps->nr) {
1619 struct child_process cp_add = CHILD_PROCESS_INIT;
1620 struct child_process cp_diff = CHILD_PROCESS_INIT;
1621 struct child_process cp_apply = CHILD_PROCESS_INIT;
1622 struct strbuf out = STRBUF_INIT;
1623
1624 cp_add.git_cmd = 1;
1625 strvec_push(&cp_add.args, "add");
1626 if (!include_untracked)
1627 strvec_push(&cp_add.args, "-u");
1628 if (include_untracked == INCLUDE_ALL_FILES)
1629 strvec_push(&cp_add.args, "--force");
1630 strvec_push(&cp_add.args, "--");
1631 add_pathspecs(&cp_add.args, ps);
1632 if (run_command(&cp_add)) {
1633 ret = -1;
1634 goto done;
1635 }
1636
1637 cp_diff.git_cmd = 1;
1638 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1639 "--cached", "--binary", "HEAD", "--",
1640 NULL);
1641 add_pathspecs(&cp_diff.args, ps);
1642 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1643 ret = -1;
1644 goto done;
1645 }
1646
1647 cp_apply.git_cmd = 1;
1648 strvec_pushl(&cp_apply.args, "apply", "--index",
1649 "-R", NULL);
1650 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1651 NULL, 0)) {
1652 ret = -1;
1653 goto done;
1654 }
1655 } else {
1656 struct child_process cp = CHILD_PROCESS_INIT;
1657 cp.git_cmd = 1;
1658 /* BUG: this nukes untracked files in the way */
1659 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1660 "--no-recurse-submodules", NULL);
1661 if (run_command(&cp)) {
1662 ret = -1;
1663 goto done;
1664 }
1665 }
1666
1667 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1668 struct child_process cp = CHILD_PROCESS_INIT;
1669
1670 cp.git_cmd = 1;
1671 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1672 oid_to_hex(&info.i_tree), "--", NULL);
1673 if (!ps->nr)
1674 strvec_push(&cp.args, ":/");
1675 else
1676 add_pathspecs(&cp.args, ps);
1677 if (run_command(&cp)) {
1678 ret = -1;
1679 goto done;
1680 }
1681 }
1682 goto done;
1683 } else {
1684 struct child_process cp = CHILD_PROCESS_INIT;
1685
1686 cp.git_cmd = 1;
1687 strvec_pushl(&cp.args, "apply", "-R", NULL);
1688
1689 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1690 if (!quiet)
1691 fprintf_ln(stderr, _("Cannot remove "
1692 "worktree changes"));
1693 ret = -1;
1694 goto done;
1695 }
1696
1697 if (keep_index < 1) {
1698 struct child_process cp = CHILD_PROCESS_INIT;
1699
1700 cp.git_cmd = 1;
1701 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1702 NULL);
1703 add_pathspecs(&cp.args, ps);
1704 if (run_command(&cp)) {
1705 ret = -1;
1706 goto done;
1707 }
1708 }
1709 goto done;
1710 }
1711
1712 done:
1713 strbuf_release(&patch);
1714 free_stash_info(&info);
1715 strbuf_release(&stash_msg_buf);
1716 strbuf_release(&untracked_files);
1717 return ret;
1718 }
1719
1720 static int push_stash(int argc, const char **argv, const char *prefix,
1721 int push_assumed)
1722 {
1723 int force_assume = 0;
1724 int keep_index = -1;
1725 int only_staged = 0;
1726 int patch_mode = 0;
1727 int include_untracked = 0;
1728 int quiet = 0;
1729 int pathspec_file_nul = 0;
1730 const char *stash_msg = NULL;
1731 const char *pathspec_from_file = NULL;
1732 struct pathspec ps;
1733 struct option options[] = {
1734 OPT_BOOL('k', "keep-index", &keep_index,
1735 N_("keep index")),
1736 OPT_BOOL('S', "staged", &only_staged,
1737 N_("stash staged changes only")),
1738 OPT_BOOL('p', "patch", &patch_mode,
1739 N_("stash in patch mode")),
1740 OPT__QUIET(&quiet, N_("quiet mode")),
1741 OPT_BOOL('u', "include-untracked", &include_untracked,
1742 N_("include untracked files in stash")),
1743 OPT_SET_INT('a', "all", &include_untracked,
1744 N_("include ignore files"), 2),
1745 OPT_STRING('m', "message", &stash_msg, N_("message"),
1746 N_("stash message")),
1747 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1748 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1749 OPT_END()
1750 };
1751 int ret;
1752
1753 if (argc) {
1754 force_assume = !strcmp(argv[0], "-p");
1755 argc = parse_options(argc, argv, prefix, options,
1756 push_assumed ? git_stash_usage :
1757 git_stash_push_usage,
1758 PARSE_OPT_KEEP_DASHDASH);
1759 }
1760
1761 if (argc) {
1762 if (!strcmp(argv[0], "--")) {
1763 argc--;
1764 argv++;
1765 } else if (push_assumed && !force_assume) {
1766 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1767 argv[0]);
1768 }
1769 }
1770
1771 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1772 prefix, argv);
1773
1774 if (pathspec_from_file) {
1775 if (patch_mode)
1776 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1777
1778 if (only_staged)
1779 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1780
1781 if (ps.nr)
1782 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1783
1784 parse_pathspec_file(&ps, 0,
1785 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1786 prefix, pathspec_from_file, pathspec_file_nul);
1787 } else if (pathspec_file_nul) {
1788 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1789 }
1790
1791 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1792 include_untracked, only_staged);
1793 clear_pathspec(&ps);
1794 return ret;
1795 }
1796
1797 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1798 {
1799 return push_stash(argc, argv, prefix, 0);
1800 }
1801
1802 static int save_stash(int argc, const char **argv, const char *prefix)
1803 {
1804 int keep_index = -1;
1805 int only_staged = 0;
1806 int patch_mode = 0;
1807 int include_untracked = 0;
1808 int quiet = 0;
1809 int ret = 0;
1810 const char *stash_msg = NULL;
1811 struct pathspec ps;
1812 struct strbuf stash_msg_buf = STRBUF_INIT;
1813 struct option options[] = {
1814 OPT_BOOL('k', "keep-index", &keep_index,
1815 N_("keep index")),
1816 OPT_BOOL('S', "staged", &only_staged,
1817 N_("stash staged changes only")),
1818 OPT_BOOL('p', "patch", &patch_mode,
1819 N_("stash in patch mode")),
1820 OPT__QUIET(&quiet, N_("quiet mode")),
1821 OPT_BOOL('u', "include-untracked", &include_untracked,
1822 N_("include untracked files in stash")),
1823 OPT_SET_INT('a', "all", &include_untracked,
1824 N_("include ignore files"), 2),
1825 OPT_STRING('m', "message", &stash_msg, "message",
1826 N_("stash message")),
1827 OPT_END()
1828 };
1829
1830 argc = parse_options(argc, argv, prefix, options,
1831 git_stash_save_usage,
1832 PARSE_OPT_KEEP_DASHDASH);
1833
1834 if (argc)
1835 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1836
1837 memset(&ps, 0, sizeof(ps));
1838 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1839 patch_mode, include_untracked, only_staged);
1840
1841 strbuf_release(&stash_msg_buf);
1842 return ret;
1843 }
1844
1845 int cmd_stash(int argc, const char **argv, const char *prefix)
1846 {
1847 pid_t pid = getpid();
1848 const char *index_file;
1849 struct strvec args = STRVEC_INIT;
1850 parse_opt_subcommand_fn *fn = NULL;
1851 struct option options[] = {
1852 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1853 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1854 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1855 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1856 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1857 OPT_SUBCOMMAND("list", &fn, list_stash),
1858 OPT_SUBCOMMAND("show", &fn, show_stash),
1859 OPT_SUBCOMMAND("store", &fn, store_stash),
1860 OPT_SUBCOMMAND("create", &fn, create_stash),
1861 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1862 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1863 OPT_END()
1864 };
1865
1866 git_config(git_stash_config, NULL);
1867
1868 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1869 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1870 PARSE_OPT_KEEP_UNKNOWN_OPT |
1871 PARSE_OPT_KEEP_DASHDASH);
1872
1873 prepare_repo_settings(the_repository);
1874 the_repository->settings.command_requires_full_index = 0;
1875
1876 index_file = get_index_file();
1877 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1878 (uintmax_t)pid);
1879
1880 if (fn)
1881 return !!fn(argc, argv, prefix);
1882 else if (!argc)
1883 return !!push_stash_unassumed(0, NULL, prefix);
1884
1885 /* Assume 'stash push' */
1886 strvec_push(&args, "push");
1887 strvec_pushv(&args, argv);
1888 return !!push_stash(args.nr, args.v, prefix, 1);
1889 }