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