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