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