]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/stash.c
rebase: do not attempt to remove startup_info->original_cwd
[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",
40af1468 30 N_("git stash [push [-p|--patch] [-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>...]]"),
40af1468 34 N_("git stash save [-p|--patch] [-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
564 return ret;
565 }
566
567 if (has_index) {
568 if (reset_tree(&index_tree, 0, 0))
569 return -1;
570 } else {
b34ab4a4 571 unstage_changes_unless_new(&c_tree);
8a0fc8d1
JT
572 }
573
bee8691f
EN
574 if (info->has_u && restore_untracked(&info->u_tree))
575 return error(_("could not restore untracked files from stash"));
576
df53c808 577 if (!quiet) {
8a0fc8d1
JT
578 struct child_process cp = CHILD_PROCESS_INIT;
579
580 /*
581 * Status is quite simple and could be replaced with calls to
582 * wt_status in the future, but it adds complexities which may
583 * require more tests.
584 */
585 cp.git_cmd = 1;
586 cp.dir = prefix;
22f9b7f3 587 strvec_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
f6d8942b 588 absolute_path(get_git_work_tree()));
22f9b7f3 589 strvec_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
f6d8942b 590 absolute_path(get_git_dir()));
22f9b7f3 591 strvec_push(&cp.args, "status");
8a0fc8d1
JT
592 run_command(&cp);
593 }
594
595 return 0;
596}
597
598static int apply_stash(int argc, const char **argv, const char *prefix)
599{
600 int ret;
601 int quiet = 0;
602 int index = 0;
603 struct stash_info info;
604 struct option options[] = {
605 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
606 OPT_BOOL(0, "index", &index,
607 N_("attempt to recreate the index")),
608 OPT_END()
609 };
610
611 argc = parse_options(argc, argv, prefix, options,
40af1468 612 git_stash_apply_usage, 0);
8a0fc8d1
JT
613
614 if (get_stash_info(&info, argc, argv))
615 return -1;
616
617 ret = do_apply_stash(prefix, &info, index, quiet);
618 free_stash_info(&info);
619 return ret;
620}
621
4f44c565
RS
622static int reject_reflog_ent(struct object_id *ooid, struct object_id *noid,
623 const char *email, timestamp_t timestamp, int tz,
624 const char *message, void *cb_data)
625{
626 return 1;
627}
628
629static int reflog_is_empty(const char *refname)
630{
631 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
632}
633
eabf7405 634static int do_drop_stash(struct stash_info *info, int quiet)
4e2dd393
JT
635{
636 int ret;
637 struct child_process cp_reflog = CHILD_PROCESS_INIT;
4e2dd393
JT
638
639 /*
640 * reflog does not provide a simple function for deleting refs. One will
641 * need to be added to avoid implementing too much reflog code here
642 */
643
644 cp_reflog.git_cmd = 1;
22f9b7f3 645 strvec_pushl(&cp_reflog.args, "reflog", "delete", "--updateref",
f6d8942b 646 "--rewrite", NULL);
22f9b7f3 647 strvec_push(&cp_reflog.args, info->revision.buf);
4e2dd393
JT
648 ret = run_command(&cp_reflog);
649 if (!ret) {
650 if (!quiet)
651 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
652 oid_to_hex(&info->w_commit));
653 } else {
654 return error(_("%s: Could not drop stash entry"),
655 info->revision.buf);
656 }
657
4f44c565 658 if (reflog_is_empty(ref_stash))
4e2dd393
JT
659 do_clear_stash();
660
661 return 0;
662}
663
664static void assert_stash_ref(struct stash_info *info)
665{
666 if (!info->is_stash_ref) {
667 error(_("'%s' is not a stash reference"), info->revision.buf);
668 free_stash_info(info);
669 exit(1);
670 }
671}
672
673static int drop_stash(int argc, const char **argv, const char *prefix)
674{
675 int ret;
676 int quiet = 0;
677 struct stash_info info;
678 struct option options[] = {
679 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
680 OPT_END()
681 };
682
683 argc = parse_options(argc, argv, prefix, options,
40af1468 684 git_stash_drop_usage, 0);
4e2dd393
JT
685
686 if (get_stash_info(&info, argc, argv))
687 return -1;
688
689 assert_stash_ref(&info);
690
eabf7405 691 ret = do_drop_stash(&info, quiet);
4e2dd393
JT
692 free_stash_info(&info);
693 return ret;
694}
695
c4de61d7
JT
696static int pop_stash(int argc, const char **argv, const char *prefix)
697{
698 int ret;
699 int index = 0;
700 int quiet = 0;
701 struct stash_info info;
702 struct option options[] = {
703 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
704 OPT_BOOL(0, "index", &index,
705 N_("attempt to recreate the index")),
706 OPT_END()
707 };
708
709 argc = parse_options(argc, argv, prefix, options,
40af1468 710 git_stash_pop_usage, 0);
c4de61d7
JT
711
712 if (get_stash_info(&info, argc, argv))
713 return -1;
714
715 assert_stash_ref(&info);
716 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
717 printf_ln(_("The stash entry is kept in case "
718 "you need it again."));
719 else
eabf7405 720 ret = do_drop_stash(&info, quiet);
c4de61d7
JT
721
722 free_stash_info(&info);
723 return ret;
724}
725
577c1995
JT
726static int branch_stash(int argc, const char **argv, const char *prefix)
727{
728 int ret;
729 const char *branch = NULL;
730 struct stash_info info;
731 struct child_process cp = CHILD_PROCESS_INIT;
732 struct option options[] = {
733 OPT_END()
734 };
735
736 argc = parse_options(argc, argv, prefix, options,
40af1468 737 git_stash_branch_usage, 0);
577c1995
JT
738
739 if (!argc) {
740 fprintf_ln(stderr, _("No branch name specified"));
741 return -1;
742 }
743
744 branch = argv[0];
745
746 if (get_stash_info(&info, argc - 1, argv + 1))
747 return -1;
748
749 cp.git_cmd = 1;
22f9b7f3
JK
750 strvec_pushl(&cp.args, "checkout", "-b", NULL);
751 strvec_push(&cp.args, branch);
752 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
577c1995
JT
753 ret = run_command(&cp);
754 if (!ret)
755 ret = do_apply_stash(prefix, &info, 1, 0);
756 if (!ret && info.is_stash_ref)
eabf7405 757 ret = do_drop_stash(&info, 0);
577c1995
JT
758
759 free_stash_info(&info);
760
761 return ret;
762}
763
130f2697
PSU
764static int list_stash(int argc, const char **argv, const char *prefix)
765{
766 struct child_process cp = CHILD_PROCESS_INIT;
767 struct option options[] = {
768 OPT_END()
769 };
770
771 argc = parse_options(argc, argv, prefix, options,
40af1468 772 git_stash_list_usage,
130f2697
PSU
773 PARSE_OPT_KEEP_UNKNOWN);
774
775 if (!ref_exists(ref_stash))
776 return 0;
777
778 cp.git_cmd = 1;
22f9b7f3 779 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
1e20a407 780 "--first-parent", NULL);
22f9b7f3
JK
781 strvec_pushv(&cp.args, argv);
782 strvec_push(&cp.args, ref_stash);
783 strvec_push(&cp.args, "--");
130f2697
PSU
784 return run_command(&cp);
785}
786
dc7bd382
PSU
787static int show_stat = 1;
788static int show_patch;
0af760e2 789static int show_include_untracked;
8a2cd3f5 790static int use_legacy_stash;
dc7bd382
PSU
791
792static int git_stash_config(const char *var, const char *value, void *cb)
793{
794 if (!strcmp(var, "stash.showstat")) {
795 show_stat = git_config_bool(var, value);
796 return 0;
797 }
798 if (!strcmp(var, "stash.showpatch")) {
799 show_patch = git_config_bool(var, value);
800 return 0;
801 }
0af760e2
DL
802 if (!strcmp(var, "stash.showincludeuntracked")) {
803 show_include_untracked = git_config_bool(var, value);
804 return 0;
805 }
8a2cd3f5
TG
806 if (!strcmp(var, "stash.usebuiltin")) {
807 use_legacy_stash = !git_config_bool(var, value);
808 return 0;
809 }
b0c7362d 810 return git_diff_basic_config(var, value, cb);
dc7bd382
PSU
811}
812
d3c7bf73
DL
813static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
814{
815 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
816 struct tree *tree[ARRAY_SIZE(oid)];
817 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
818 struct unpack_trees_options unpack_tree_opt = { 0 };
819 int i;
820
821 for (i = 0; i < ARRAY_SIZE(oid); i++) {
822 tree[i] = parse_tree_indirect(oid[i]);
823 if (parse_tree(tree[i]) < 0)
824 die(_("failed to parse tree"));
825 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
826 }
827
828 unpack_tree_opt.head_idx = -1;
829 unpack_tree_opt.src_index = &the_index;
830 unpack_tree_opt.dst_index = &the_index;
831 unpack_tree_opt.merge = 1;
832 unpack_tree_opt.fn = stash_worktree_untracked_merge;
833
834 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
835 die(_("failed to unpack trees"));
836
837 do_diff_cache(&info->b_commit, diff_opt);
838}
839
dc7bd382
PSU
840static int show_stash(int argc, const char **argv, const char *prefix)
841{
842 int i;
dc7bd382
PSU
843 int ret = 0;
844 struct stash_info info;
845 struct rev_info rev;
22f9b7f3
JK
846 struct strvec stash_args = STRVEC_INIT;
847 struct strvec revision_args = STRVEC_INIT;
d3c7bf73
DL
848 enum {
849 UNTRACKED_NONE,
850 UNTRACKED_INCLUDE,
851 UNTRACKED_ONLY
af5cd44b 852 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
dc7bd382 853 struct option options[] = {
d3c7bf73
DL
854 OPT_SET_INT('u', "include-untracked", &show_untracked,
855 N_("include untracked files in the stash"),
856 UNTRACKED_INCLUDE),
857 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
858 N_("only show untracked files in the stash"),
859 UNTRACKED_ONLY, PARSE_OPT_NONEG),
dc7bd382
PSU
860 OPT_END()
861 };
862
863 init_diff_ui_defaults();
864 git_config(git_diff_ui_config, NULL);
865 init_revisions(&rev, prefix);
866
d3c7bf73
DL
867 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
868 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
869 PARSE_OPT_KEEP_DASHDASH);
870
22f9b7f3 871 strvec_push(&revision_args, argv[0]);
dc7bd382
PSU
872 for (i = 1; i < argc; i++) {
873 if (argv[i][0] != '-')
22f9b7f3 874 strvec_push(&stash_args, argv[i]);
dc7bd382 875 else
22f9b7f3 876 strvec_push(&revision_args, argv[i]);
dc7bd382
PSU
877 }
878
d70a9eb6 879 ret = get_stash_info(&info, stash_args.nr, stash_args.v);
22f9b7f3 880 strvec_clear(&stash_args);
dc7bd382
PSU
881 if (ret)
882 return -1;
883
884 /*
885 * The config settings are applied only if there are not passed
886 * any options.
887 */
d70a9eb6 888 if (revision_args.nr == 1) {
dc7bd382
PSU
889 if (show_stat)
890 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
891
892 if (show_patch)
893 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
894
895 if (!show_stat && !show_patch) {
896 free_stash_info(&info);
897 return 0;
898 }
899 }
900
d70a9eb6 901 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
dc7bd382
PSU
902 if (argc > 1) {
903 free_stash_info(&info);
40af1468 904 usage_with_options(git_stash_show_usage, options);
dc7bd382 905 }
8e407bc8
TG
906 if (!rev.diffopt.output_format) {
907 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
908 diff_setup_done(&rev.diffopt);
909 }
dc7bd382
PSU
910
911 rev.diffopt.flags.recursive = 1;
912 setup_diff_pager(&rev.diffopt);
d3c7bf73
DL
913 switch (show_untracked) {
914 case UNTRACKED_NONE:
915 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
916 break;
917 case UNTRACKED_ONLY:
1ff595d2
DL
918 if (info.has_u)
919 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
d3c7bf73
DL
920 break;
921 case UNTRACKED_INCLUDE:
1ff595d2
DL
922 if (info.has_u)
923 diff_include_untracked(&info, &rev.diffopt);
924 else
925 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
d3c7bf73
DL
926 break;
927 }
dc7bd382
PSU
928 log_tree_diff_flush(&rev);
929
930 free_stash_info(&info);
931 return diff_result_code(&rev.diffopt, 0);
932}
933
41e0dd55
PSU
934static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
935 int quiet)
936{
937 if (!stash_msg)
938 stash_msg = "Created via \"git stash store\".";
939
940 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
941 REF_FORCE_CREATE_REFLOG,
942 quiet ? UPDATE_REFS_QUIET_ON_ERR :
943 UPDATE_REFS_MSG_ON_ERR)) {
944 if (!quiet) {
945 fprintf_ln(stderr, _("Cannot update %s with %s"),
946 ref_stash, oid_to_hex(w_commit));
947 }
948 return -1;
949 }
950
951 return 0;
952}
953
954static int store_stash(int argc, const char **argv, const char *prefix)
955{
956 int quiet = 0;
957 const char *stash_msg = NULL;
958 struct object_id obj;
959 struct object_context dummy;
960 struct option options[] = {
961 OPT__QUIET(&quiet, N_("be quiet")),
962 OPT_STRING('m', "message", &stash_msg, "message",
963 N_("stash message")),
964 OPT_END()
965 };
966
967 argc = parse_options(argc, argv, prefix, options,
40af1468 968 git_stash_store_usage,
41e0dd55
PSU
969 PARSE_OPT_KEEP_UNKNOWN);
970
971 if (argc != 1) {
972 if (!quiet)
973 fprintf_ln(stderr, _("\"git stash store\" requires one "
974 "<commit> argument"));
975 return -1;
976 }
977
e36adf71
JH
978 if (get_oid_with_context(the_repository,
979 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
41e0dd55
PSU
980 &dummy)) {
981 if (!quiet)
982 fprintf_ln(stderr, _("Cannot update %s with %s"),
983 ref_stash, argv[0]);
984 return -1;
985 }
986
987 return do_store_stash(&obj, stash_msg, quiet);
988}
989
22f9b7f3 990static void add_pathspecs(struct strvec *args,
7db9302d 991 const struct pathspec *ps) {
d4788af8
PSU
992 int i;
993
7db9302d 994 for (i = 0; i < ps->nr; i++)
22f9b7f3 995 strvec_push(args, ps->items[i].original);
d4788af8
PSU
996}
997
998/*
999 * `untracked_files` will be filled with the names of untracked files.
1000 * The return value is:
1001 *
1002 * = 0 if there are not any untracked files
1003 * > 0 if there are untracked files
1004 */
7db9302d 1005static int get_untracked_files(const struct pathspec *ps, int include_untracked,
d4788af8
PSU
1006 struct strbuf *untracked_files)
1007{
1008 int i;
d4788af8 1009 int found = 0;
ce93a4c6 1010 struct dir_struct dir = DIR_INIT;
d4788af8 1011
d4788af8
PSU
1012 if (include_untracked != INCLUDE_ALL_FILES)
1013 setup_standard_excludes(&dir);
1014
95c11ecc 1015 fill_directory(&dir, the_repository->index, ps);
d4788af8
PSU
1016 for (i = 0; i < dir.nr; i++) {
1017 struct dir_entry *ent = dir.entries[i];
95c11ecc
EN
1018 found++;
1019 strbuf_addstr(untracked_files, ent->name);
1020 /* NUL-terminate: will be fed to update-index -z */
1021 strbuf_addch(untracked_files, '\0');
d4788af8
PSU
1022 }
1023
eceba532 1024 dir_clear(&dir);
d4788af8
PSU
1025 return found;
1026}
1027
1028/*
ef0f0b45 1029 * The return value of `check_changes_tracked_files()` can be:
d4788af8
PSU
1030 *
1031 * < 0 if there was an error
1032 * = 0 if there are no changes.
1033 * > 0 if there are changes.
1034 */
7db9302d 1035static int check_changes_tracked_files(const struct pathspec *ps)
d4788af8
PSU
1036{
1037 int result;
1038 struct rev_info rev;
1039 struct object_id dummy;
7db9302d 1040 int ret = 0;
d4788af8
PSU
1041
1042 /* No initial commit. */
1043 if (get_oid("HEAD", &dummy))
1044 return -1;
1045
1046 if (read_cache() < 0)
1047 return -1;
1048
1049 init_revisions(&rev, NULL);
7db9302d 1050 copy_pathspec(&rev.prune_data, ps);
d4788af8
PSU
1051
1052 rev.diffopt.flags.quick = 1;
1053 rev.diffopt.flags.ignore_submodules = 1;
1054 rev.abbrev = 0;
1055
1056 add_head_to_pending(&rev);
1057 diff_setup_done(&rev.diffopt);
1058
1059 result = run_diff_index(&rev, 1);
7db9302d
TG
1060 if (diff_result_code(&rev.diffopt, result)) {
1061 ret = 1;
1062 goto done;
1063 }
d4788af8
PSU
1064
1065 object_array_clear(&rev.pending);
1066 result = run_diff_files(&rev, 0);
7db9302d
TG
1067 if (diff_result_code(&rev.diffopt, result)) {
1068 ret = 1;
1069 goto done;
1070 }
d4788af8 1071
7db9302d
TG
1072done:
1073 clear_pathspec(&rev.prune_data);
1074 return ret;
ef0f0b45
PSU
1075}
1076
1077/*
1078 * The function will fill `untracked_files` with the names of untracked files
1079 * It will return 1 if there were any changes and 0 if there were not.
1080 */
7db9302d 1081static int check_changes(const struct pathspec *ps, int include_untracked,
ef0f0b45
PSU
1082 struct strbuf *untracked_files)
1083{
1084 int ret = 0;
1085 if (check_changes_tracked_files(ps))
1086 ret = 1;
1087
d4788af8 1088 if (include_untracked && get_untracked_files(ps, include_untracked,
ef0f0b45
PSU
1089 untracked_files))
1090 ret = 1;
d4788af8 1091
ef0f0b45 1092 return ret;
d4788af8
PSU
1093}
1094
1095static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1096 struct strbuf files)
1097{
1098 int ret = 0;
1099 struct strbuf untracked_msg = STRBUF_INIT;
d4788af8 1100 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
48ee24ab 1101 struct index_state istate = { NULL };
d4788af8
PSU
1102
1103 cp_upd_index.git_cmd = 1;
22f9b7f3 1104 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
f6d8942b 1105 "--remove", "--stdin", NULL);
22f9b7f3 1106 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
d4788af8
PSU
1107 stash_index_path.buf);
1108
1109 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1110 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1111 NULL, 0)) {
1112 ret = -1;
1113 goto done;
1114 }
1115
48ee24ab
PSU
1116 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1117 NULL)) {
d4788af8
PSU
1118 ret = -1;
1119 goto done;
1120 }
d4788af8
PSU
1121
1122 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1123 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1124 ret = -1;
1125 goto done;
1126 }
1127
1128done:
48ee24ab 1129 discard_index(&istate);
d4788af8 1130 strbuf_release(&untracked_msg);
d4788af8
PSU
1131 remove_path(stash_index_path.buf);
1132 return ret;
1133}
1134
7db9302d 1135static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1ac528c0 1136 struct strbuf *out_patch, int quiet)
d4788af8
PSU
1137{
1138 int ret = 0;
d4788af8 1139 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
d4788af8 1140 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
48ee24ab 1141 struct index_state istate = { NULL };
6610e462 1142 char *old_index_env = NULL, *old_repo_index_file;
d4788af8
PSU
1143
1144 remove_path(stash_index_path.buf);
1145
1146 cp_read_tree.git_cmd = 1;
22f9b7f3
JK
1147 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1148 strvec_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
f6d8942b 1149 stash_index_path.buf);
d4788af8
PSU
1150 if (run_command(&cp_read_tree)) {
1151 ret = -1;
1152 goto done;
1153 }
1154
1155 /* Find out what the user wants. */
6610e462
JS
1156 old_repo_index_file = the_repository->index_file;
1157 the_repository->index_file = stash_index_path.buf;
1158 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1159 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1160
1161 ret = run_add_interactive(NULL, "--patch=stash", ps);
1162
1163 the_repository->index_file = old_repo_index_file;
1164 if (old_index_env && *old_index_env)
1165 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1166 else
1167 unsetenv(INDEX_ENVIRONMENT);
1168 FREE_AND_NULL(old_index_env);
d4788af8
PSU
1169
1170 /* State of the working tree. */
48ee24ab
PSU
1171 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1172 NULL)) {
d4788af8
PSU
1173 ret = -1;
1174 goto done;
1175 }
1176
d4788af8 1177 cp_diff_tree.git_cmd = 1;
22f9b7f3 1178 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
f6d8942b 1179 oid_to_hex(&info->w_tree), "--", NULL);
d4788af8
PSU
1180 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1181 ret = -1;
1182 goto done;
1183 }
1184
1185 if (!out_patch->len) {
1ac528c0
PSU
1186 if (!quiet)
1187 fprintf_ln(stderr, _("No changes selected"));
d4788af8
PSU
1188 ret = 1;
1189 }
1190
1191done:
48ee24ab 1192 discard_index(&istate);
d4788af8
PSU
1193 remove_path(stash_index_path.buf);
1194 return ret;
1195}
1196
7db9302d 1197static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
d4788af8
PSU
1198{
1199 int ret = 0;
1200 struct rev_info rev;
1201 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
d4788af8 1202 struct strbuf diff_output = STRBUF_INIT;
48ee24ab 1203 struct index_state istate = { NULL };
d4788af8
PSU
1204
1205 init_revisions(&rev, NULL);
7db9302d 1206 copy_pathspec(&rev.prune_data, ps);
d4788af8
PSU
1207
1208 set_alternate_index_output(stash_index_path.buf);
1209 if (reset_tree(&info->i_tree, 0, 0)) {
1210 ret = -1;
1211 goto done;
1212 }
1213 set_alternate_index_output(NULL);
1214
d4788af8
PSU
1215 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1216 rev.diffopt.format_callback = add_diff_to_buf;
1217 rev.diffopt.format_callback_data = &diff_output;
1218
1219 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1220 ret = -1;
1221 goto done;
1222 }
1223
1224 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1225 "");
1226 if (run_diff_index(&rev, 0)) {
1227 ret = -1;
1228 goto done;
1229 }
1230
1231 cp_upd_index.git_cmd = 1;
22f9b7f3 1232 strvec_pushl(&cp_upd_index.args, "update-index",
f6d8942b
JK
1233 "--ignore-skip-worktree-entries",
1234 "-z", "--add", "--remove", "--stdin", NULL);
22f9b7f3 1235 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
f6d8942b 1236 stash_index_path.buf);
d4788af8
PSU
1237
1238 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1239 NULL, 0, NULL, 0)) {
1240 ret = -1;
1241 goto done;
1242 }
1243
48ee24ab
PSU
1244 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1245 NULL)) {
d4788af8
PSU
1246 ret = -1;
1247 goto done;
1248 }
1249
d4788af8 1250done:
48ee24ab 1251 discard_index(&istate);
d4788af8 1252 UNLEAK(rev);
d4788af8 1253 object_array_clear(&rev.pending);
7db9302d 1254 clear_pathspec(&rev.prune_data);
d4788af8
PSU
1255 strbuf_release(&diff_output);
1256 remove_path(stash_index_path.buf);
1257 return ret;
1258}
1259
7db9302d 1260static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
d4788af8 1261 int include_untracked, int patch_mode,
1ac528c0
PSU
1262 struct stash_info *info, struct strbuf *patch,
1263 int quiet)
d4788af8
PSU
1264{
1265 int ret = 0;
1266 int flags = 0;
1267 int untracked_commit_option = 0;
1268 const char *head_short_sha1 = NULL;
1269 const char *branch_ref = NULL;
1270 const char *branch_name = "(no branch)";
1271 struct commit *head_commit = NULL;
1272 struct commit_list *parents = NULL;
1273 struct strbuf msg = STRBUF_INIT;
1274 struct strbuf commit_tree_label = STRBUF_INIT;
1275 struct strbuf untracked_files = STRBUF_INIT;
d4788af8
PSU
1276
1277 prepare_fallback_ident("git stash", "git@stash");
1278
1279 read_cache_preload(NULL);
34933d0e
TG
1280 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1281 ret = -1;
1282 goto done;
1283 }
d4788af8
PSU
1284
1285 if (get_oid("HEAD", &info->b_commit)) {
1ac528c0
PSU
1286 if (!quiet)
1287 fprintf_ln(stderr, _("You do not have "
1288 "the initial commit yet"));
d4788af8
PSU
1289 ret = -1;
1290 goto done;
1291 } else {
1292 head_commit = lookup_commit(the_repository, &info->b_commit);
1293 }
1294
ef0f0b45 1295 if (!check_changes(ps, include_untracked, &untracked_files)) {
d4788af8
PSU
1296 ret = 1;
1297 goto done;
1298 }
1299
1300 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1301 if (flags & REF_ISSYMREF)
1302 branch_name = strrchr(branch_ref, '/') + 1;
1303 head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1304 DEFAULT_ABBREV);
1305 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1306 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1307
1308 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1309 commit_list_insert(head_commit, &parents);
1310 if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1311 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1312 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1ac528c0
PSU
1313 if (!quiet)
1314 fprintf_ln(stderr, _("Cannot save the current "
1315 "index state"));
d4788af8
PSU
1316 ret = -1;
1317 goto done;
1318 }
1319
ef0f0b45 1320 if (include_untracked) {
d4788af8 1321 if (save_untracked_files(info, &msg, untracked_files)) {
1ac528c0
PSU
1322 if (!quiet)
1323 fprintf_ln(stderr, _("Cannot save "
1324 "the untracked files"));
d4788af8
PSU
1325 ret = -1;
1326 goto done;
1327 }
1328 untracked_commit_option = 1;
1329 }
1330 if (patch_mode) {
1ac528c0 1331 ret = stash_patch(info, ps, patch, quiet);
d4788af8 1332 if (ret < 0) {
1ac528c0
PSU
1333 if (!quiet)
1334 fprintf_ln(stderr, _("Cannot save the current "
1335 "worktree state"));
d4788af8
PSU
1336 goto done;
1337 } else if (ret > 0) {
1338 goto done;
1339 }
1340 } else {
1341 if (stash_working_tree(info, ps)) {
1ac528c0
PSU
1342 if (!quiet)
1343 fprintf_ln(stderr, _("Cannot save the current "
1344 "worktree state"));
d4788af8
PSU
1345 ret = -1;
1346 goto done;
1347 }
1348 }
1349
1350 if (!stash_msg_buf->len)
1351 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1352 else
1353 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1354
1355 /*
1356 * `parents` will be empty after calling `commit_tree()`, so there is
1357 * no need to call `free_commit_list()`
1358 */
1359 parents = NULL;
1360 if (untracked_commit_option)
1361 commit_list_insert(lookup_commit(the_repository,
1362 &info->u_commit),
1363 &parents);
1364 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1365 &parents);
1366 commit_list_insert(head_commit, &parents);
1367
1368 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1369 parents, &info->w_commit, NULL, NULL)) {
1ac528c0
PSU
1370 if (!quiet)
1371 fprintf_ln(stderr, _("Cannot record "
1372 "working tree state"));
d4788af8
PSU
1373 ret = -1;
1374 goto done;
1375 }
1376
1377done:
1378 strbuf_release(&commit_tree_label);
1379 strbuf_release(&msg);
1380 strbuf_release(&untracked_files);
1381 return ret;
1382}
1383
1384static int create_stash(int argc, const char **argv, const char *prefix)
1385{
d4788af8 1386 int ret = 0;
d4788af8
PSU
1387 struct strbuf stash_msg_buf = STRBUF_INIT;
1388 struct stash_info info;
1389 struct pathspec ps;
d4788af8 1390
40af1468
PSU
1391 /* Starting with argv[1], since argv[0] is "create" */
1392 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
d4788af8
PSU
1393
1394 memset(&ps, 0, sizeof(ps));
7db9302d 1395 if (!check_changes_tracked_files(&ps))
ef0f0b45
PSU
1396 return 0;
1397
7db9302d 1398 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, &info,
1ac528c0 1399 NULL, 0);
d4788af8
PSU
1400 if (!ret)
1401 printf_ln("%s", oid_to_hex(&info.w_commit));
1402
1403 strbuf_release(&stash_msg_buf);
ef0f0b45 1404 return ret;
d4788af8
PSU
1405}
1406
7db9302d 1407static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
d553f538
PSU
1408 int keep_index, int patch_mode, int include_untracked)
1409{
1410 int ret = 0;
1411 struct stash_info info;
1412 struct strbuf patch = STRBUF_INIT;
1413 struct strbuf stash_msg_buf = STRBUF_INIT;
ef0f0b45 1414 struct strbuf untracked_files = STRBUF_INIT;
d553f538
PSU
1415
1416 if (patch_mode && keep_index == -1)
1417 keep_index = 1;
1418
1419 if (patch_mode && include_untracked) {
1420 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1421 " or --all at the same time"));
1422 ret = -1;
1423 goto done;
1424 }
1425
1426 read_cache_preload(NULL);
7db9302d 1427 if (!include_untracked && ps->nr) {
d553f538 1428 int i;
7db9302d 1429 char *ps_matched = xcalloc(ps->nr, 1);
d553f538 1430
a0291201
DS
1431 /* TODO: audit for interaction with sparse-index. */
1432 ensure_full_index(&the_index);
d553f538 1433 for (i = 0; i < active_nr; i++)
7db9302d 1434 ce_path_match(&the_index, active_cache[i], ps,
d553f538
PSU
1435 ps_matched);
1436
42844973 1437 if (report_path_error(ps_matched, ps)) {
d553f538
PSU
1438 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1439 ret = -1;
1440 free(ps_matched);
1441 goto done;
1442 }
1443 free(ps_matched);
1444 }
1445
34933d0e 1446 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
d553f538
PSU
1447 ret = -1;
1448 goto done;
1449 }
1450
ef0f0b45 1451 if (!check_changes(ps, include_untracked, &untracked_files)) {
d553f538
PSU
1452 if (!quiet)
1453 printf_ln(_("No local changes to save"));
1454 goto done;
1455 }
1456
1457 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1458 ret = -1;
1ac528c0
PSU
1459 if (!quiet)
1460 fprintf_ln(stderr, _("Cannot initialize stash"));
d553f538
PSU
1461 goto done;
1462 }
1463
1464 if (stash_msg)
1465 strbuf_addstr(&stash_msg_buf, stash_msg);
1466 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1ac528c0 1467 &info, &patch, quiet)) {
d553f538
PSU
1468 ret = -1;
1469 goto done;
1470 }
1471
1472 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1473 ret = -1;
1ac528c0
PSU
1474 if (!quiet)
1475 fprintf_ln(stderr, _("Cannot save the current status"));
d553f538
PSU
1476 goto done;
1477 }
1478
1ac528c0
PSU
1479 if (!quiet)
1480 printf_ln(_("Saved working directory and index state %s"),
1481 stash_msg_buf.buf);
d553f538
PSU
1482
1483 if (!patch_mode) {
7db9302d 1484 if (include_untracked && !ps->nr) {
d553f538
PSU
1485 struct child_process cp = CHILD_PROCESS_INIT;
1486
1487 cp.git_cmd = 1;
22f9b7f3 1488 strvec_pushl(&cp.args, "clean", "--force",
f6d8942b 1489 "--quiet", "-d", NULL);
d553f538 1490 if (include_untracked == INCLUDE_ALL_FILES)
22f9b7f3 1491 strvec_push(&cp.args, "-x");
d553f538
PSU
1492 if (run_command(&cp)) {
1493 ret = -1;
1494 goto done;
1495 }
1496 }
1497 discard_cache();
7db9302d 1498 if (ps->nr) {
d553f538
PSU
1499 struct child_process cp_add = CHILD_PROCESS_INIT;
1500 struct child_process cp_diff = CHILD_PROCESS_INIT;
1501 struct child_process cp_apply = CHILD_PROCESS_INIT;
1502 struct strbuf out = STRBUF_INIT;
1503
1504 cp_add.git_cmd = 1;
22f9b7f3 1505 strvec_push(&cp_add.args, "add");
d553f538 1506 if (!include_untracked)
22f9b7f3 1507 strvec_push(&cp_add.args, "-u");
d553f538 1508 if (include_untracked == INCLUDE_ALL_FILES)
22f9b7f3
JK
1509 strvec_push(&cp_add.args, "--force");
1510 strvec_push(&cp_add.args, "--");
d553f538
PSU
1511 add_pathspecs(&cp_add.args, ps);
1512 if (run_command(&cp_add)) {
1513 ret = -1;
1514 goto done;
1515 }
1516
1517 cp_diff.git_cmd = 1;
22f9b7f3 1518 strvec_pushl(&cp_diff.args, "diff-index", "-p",
f6d8942b
JK
1519 "--cached", "--binary", "HEAD", "--",
1520 NULL);
d553f538
PSU
1521 add_pathspecs(&cp_diff.args, ps);
1522 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1523 ret = -1;
1524 goto done;
1525 }
1526
1527 cp_apply.git_cmd = 1;
22f9b7f3 1528 strvec_pushl(&cp_apply.args, "apply", "--index",
f6d8942b 1529 "-R", NULL);
d553f538
PSU
1530 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1531 NULL, 0)) {
1532 ret = -1;
1533 goto done;
1534 }
1535 } else {
1536 struct child_process cp = CHILD_PROCESS_INIT;
1537 cp.git_cmd = 1;
94b7f156 1538 /* BUG: this nukes untracked files in the way */
22f9b7f3 1539 strvec_pushl(&cp.args, "reset", "--hard", "-q",
f6d8942b 1540 "--no-recurse-submodules", NULL);
d553f538
PSU
1541 if (run_command(&cp)) {
1542 ret = -1;
1543 goto done;
1544 }
1545 }
1546
1547 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
b932f6a5 1548 struct child_process cp = CHILD_PROCESS_INIT;
d553f538 1549
b932f6a5 1550 cp.git_cmd = 1;
22f9b7f3 1551 strvec_pushl(&cp.args, "checkout", "--no-overlay",
f6d8942b 1552 oid_to_hex(&info.i_tree), "--", NULL);
b932f6a5 1553 if (!ps->nr)
22f9b7f3 1554 strvec_push(&cp.args, ":/");
b932f6a5
TG
1555 else
1556 add_pathspecs(&cp.args, ps);
1557 if (run_command(&cp)) {
d553f538
PSU
1558 ret = -1;
1559 goto done;
1560 }
1561 }
1562 goto done;
1563 } else {
1564 struct child_process cp = CHILD_PROCESS_INIT;
1565
1566 cp.git_cmd = 1;
22f9b7f3 1567 strvec_pushl(&cp.args, "apply", "-R", NULL);
d553f538
PSU
1568
1569 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1ac528c0
PSU
1570 if (!quiet)
1571 fprintf_ln(stderr, _("Cannot remove "
1572 "worktree changes"));
d553f538
PSU
1573 ret = -1;
1574 goto done;
1575 }
1576
1577 if (keep_index < 1) {
1578 struct child_process cp = CHILD_PROCESS_INIT;
1579
1580 cp.git_cmd = 1;
22f9b7f3 1581 strvec_pushl(&cp.args, "reset", "-q", "--", NULL);
d553f538
PSU
1582 add_pathspecs(&cp.args, ps);
1583 if (run_command(&cp)) {
1584 ret = -1;
1585 goto done;
1586 }
1587 }
1588 goto done;
1589 }
1590
1591done:
1592 strbuf_release(&stash_msg_buf);
1593 return ret;
1594}
1595
8c3713ce
AM
1596static int push_stash(int argc, const char **argv, const char *prefix,
1597 int push_assumed)
d553f538 1598{
8c3713ce 1599 int force_assume = 0;
d553f538
PSU
1600 int keep_index = -1;
1601 int patch_mode = 0;
1602 int include_untracked = 0;
1603 int quiet = 0;
8a98758a 1604 int pathspec_file_nul = 0;
d553f538 1605 const char *stash_msg = NULL;
8a98758a 1606 const char *pathspec_from_file = NULL;
d553f538
PSU
1607 struct pathspec ps;
1608 struct option options[] = {
1609 OPT_BOOL('k', "keep-index", &keep_index,
1610 N_("keep index")),
1611 OPT_BOOL('p', "patch", &patch_mode,
1612 N_("stash in patch mode")),
1613 OPT__QUIET(&quiet, N_("quiet mode")),
1614 OPT_BOOL('u', "include-untracked", &include_untracked,
1615 N_("include untracked files in stash")),
1616 OPT_SET_INT('a', "all", &include_untracked,
1617 N_("include ignore files"), 2),
1618 OPT_STRING('m', "message", &stash_msg, N_("message"),
1619 N_("stash message")),
8a98758a
AM
1620 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1621 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
d553f538
PSU
1622 OPT_END()
1623 };
1624
8c3713ce
AM
1625 if (argc) {
1626 force_assume = !strcmp(argv[0], "-p");
40af1468
PSU
1627 argc = parse_options(argc, argv, prefix, options,
1628 git_stash_push_usage,
8c3713ce
AM
1629 PARSE_OPT_KEEP_DASHDASH);
1630 }
1631
1632 if (argc) {
1633 if (!strcmp(argv[0], "--")) {
1634 argc--;
1635 argv++;
1636 } else if (push_assumed && !force_assume) {
1637 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1638 argv[0]);
1639 }
1640 }
d553f538 1641
1366c78c
JS
1642 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1643 prefix, argv);
8a98758a
AM
1644
1645 if (pathspec_from_file) {
1646 if (patch_mode)
1647 die(_("--pathspec-from-file is incompatible with --patch"));
1648
1649 if (ps.nr)
1650 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1651
1652 parse_pathspec_file(&ps, 0,
1653 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1654 prefix, pathspec_from_file, pathspec_file_nul);
1655 } else if (pathspec_file_nul) {
1656 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1657 }
1658
7db9302d 1659 return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
d553f538
PSU
1660 include_untracked);
1661}
1662
64fe9c26
PSU
1663static int save_stash(int argc, const char **argv, const char *prefix)
1664{
1665 int keep_index = -1;
1666 int patch_mode = 0;
1667 int include_untracked = 0;
1668 int quiet = 0;
1669 int ret = 0;
1670 const char *stash_msg = NULL;
1671 struct pathspec ps;
1672 struct strbuf stash_msg_buf = STRBUF_INIT;
1673 struct option options[] = {
1674 OPT_BOOL('k', "keep-index", &keep_index,
1675 N_("keep index")),
1676 OPT_BOOL('p', "patch", &patch_mode,
1677 N_("stash in patch mode")),
1678 OPT__QUIET(&quiet, N_("quiet mode")),
1679 OPT_BOOL('u', "include-untracked", &include_untracked,
1680 N_("include untracked files in stash")),
1681 OPT_SET_INT('a', "all", &include_untracked,
1682 N_("include ignore files"), 2),
1683 OPT_STRING('m', "message", &stash_msg, "message",
1684 N_("stash message")),
1685 OPT_END()
1686 };
1687
1688 argc = parse_options(argc, argv, prefix, options,
40af1468 1689 git_stash_save_usage,
64fe9c26
PSU
1690 PARSE_OPT_KEEP_DASHDASH);
1691
1692 if (argc)
1693 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1694
1695 memset(&ps, 0, sizeof(ps));
7db9302d 1696 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
64fe9c26
PSU
1697 patch_mode, include_untracked);
1698
1699 strbuf_release(&stash_msg_buf);
1700 return ret;
1701}
1702
40af1468 1703int cmd_stash(int argc, const char **argv, const char *prefix)
8a0fc8d1
JT
1704{
1705 pid_t pid = getpid();
1706 const char *index_file;
22f9b7f3 1707 struct strvec args = STRVEC_INIT;
8a0fc8d1
JT
1708
1709 struct option options[] = {
1710 OPT_END()
1711 };
1712
b0c7362d 1713 git_config(git_stash_config, NULL);
90a46272 1714
8a2cd3f5
TG
1715 if (use_legacy_stash ||
1716 !git_env_bool("GIT_TEST_STASH_USE_BUILTIN", -1))
1717 warning(_("the stash.useBuiltin support has been removed!\n"
1718 "See its entry in 'git help config' for details."));
8a0fc8d1 1719
40af1468 1720 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
8a0fc8d1
JT
1721 PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1722
1723 index_file = get_index_file();
1724 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1725 (uintmax_t)pid);
1726
40af1468 1727 if (!argc)
8c3713ce 1728 return !!push_stash(0, NULL, prefix, 0);
40af1468 1729 else if (!strcmp(argv[0], "apply"))
8a0fc8d1 1730 return !!apply_stash(argc, argv, prefix);
4e2dd393
JT
1731 else if (!strcmp(argv[0], "clear"))
1732 return !!clear_stash(argc, argv, prefix);
1733 else if (!strcmp(argv[0], "drop"))
1734 return !!drop_stash(argc, argv, prefix);
c4de61d7
JT
1735 else if (!strcmp(argv[0], "pop"))
1736 return !!pop_stash(argc, argv, prefix);
577c1995
JT
1737 else if (!strcmp(argv[0], "branch"))
1738 return !!branch_stash(argc, argv, prefix);
130f2697
PSU
1739 else if (!strcmp(argv[0], "list"))
1740 return !!list_stash(argc, argv, prefix);
dc7bd382
PSU
1741 else if (!strcmp(argv[0], "show"))
1742 return !!show_stash(argc, argv, prefix);
41e0dd55
PSU
1743 else if (!strcmp(argv[0], "store"))
1744 return !!store_stash(argc, argv, prefix);
d4788af8
PSU
1745 else if (!strcmp(argv[0], "create"))
1746 return !!create_stash(argc, argv, prefix);
d553f538 1747 else if (!strcmp(argv[0], "push"))
8c3713ce 1748 return !!push_stash(argc, argv, prefix, 0);
64fe9c26
PSU
1749 else if (!strcmp(argv[0], "save"))
1750 return !!save_stash(argc, argv, prefix);
40af1468
PSU
1751 else if (*argv[0] != '-')
1752 usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1753 git_stash_usage, options);
1754
8c3713ce 1755 /* Assume 'stash push' */
22f9b7f3
JK
1756 strvec_push(&args, "push");
1757 strvec_pushv(&args, argv);
d70a9eb6 1758 return !!push_stash(args.nr, args.v, prefix, 1);
8a0fc8d1 1759}