1 #define USE_THE_REPOSITORY_VARIABLE
6 #include "environment.h"
10 #include "object-name.h"
11 #include "parse-options.h"
14 #include "cache-tree.h"
15 #include "unpack-trees.h"
16 #include "merge-ort-wrappers.h"
18 #include "run-command.h"
21 #include "preload-index.h"
22 #include "read-cache.h"
23 #include "repository.h"
27 #include "sparse-index.h"
31 #include "reflog-walk.h"
32 #include "add-interactive.h"
33 #include "oid-array.h"
36 #define INCLUDE_ALL_FILES 2
38 #define BUILTIN_STASH_LIST_USAGE \
39 N_("git stash list [<log-options>]")
40 #define BUILTIN_STASH_SHOW_USAGE \
41 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
42 #define BUILTIN_STASH_DROP_USAGE \
43 N_("git stash drop [-q | --quiet] [<stash>]")
44 #define BUILTIN_STASH_POP_USAGE \
45 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
46 #define BUILTIN_STASH_APPLY_USAGE \
47 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
48 #define BUILTIN_STASH_BRANCH_USAGE \
49 N_("git stash branch <branchname> [<stash>]")
50 #define BUILTIN_STASH_STORE_USAGE \
51 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
52 #define BUILTIN_STASH_PUSH_USAGE \
53 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
54 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
55 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
56 " [--] [<pathspec>...]]")
57 #define BUILTIN_STASH_SAVE_USAGE \
58 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
59 " [-u | --include-untracked] [-a | --all] [<message>]")
60 #define BUILTIN_STASH_CREATE_USAGE \
61 N_("git stash create [<message>]")
62 #define BUILTIN_STASH_EXPORT_USAGE \
63 N_("git stash export (--print | --to-ref <ref>) [<stash>...]")
64 #define BUILTIN_STASH_IMPORT_USAGE \
65 N_("git stash import <commit>")
66 #define BUILTIN_STASH_CLEAR_USAGE \
69 static const char * const git_stash_usage
[] = {
70 BUILTIN_STASH_LIST_USAGE
,
71 BUILTIN_STASH_SHOW_USAGE
,
72 BUILTIN_STASH_DROP_USAGE
,
73 BUILTIN_STASH_POP_USAGE
,
74 BUILTIN_STASH_APPLY_USAGE
,
75 BUILTIN_STASH_BRANCH_USAGE
,
76 BUILTIN_STASH_PUSH_USAGE
,
77 BUILTIN_STASH_SAVE_USAGE
,
78 BUILTIN_STASH_CLEAR_USAGE
,
79 BUILTIN_STASH_CREATE_USAGE
,
80 BUILTIN_STASH_STORE_USAGE
,
81 BUILTIN_STASH_EXPORT_USAGE
,
82 BUILTIN_STASH_IMPORT_USAGE
,
86 static const char * const git_stash_list_usage
[] = {
87 BUILTIN_STASH_LIST_USAGE
,
91 static const char * const git_stash_show_usage
[] = {
92 BUILTIN_STASH_SHOW_USAGE
,
96 static const char * const git_stash_drop_usage
[] = {
97 BUILTIN_STASH_DROP_USAGE
,
101 static const char * const git_stash_pop_usage
[] = {
102 BUILTIN_STASH_POP_USAGE
,
106 static const char * const git_stash_apply_usage
[] = {
107 BUILTIN_STASH_APPLY_USAGE
,
111 static const char * const git_stash_branch_usage
[] = {
112 BUILTIN_STASH_BRANCH_USAGE
,
116 static const char * const git_stash_clear_usage
[] = {
117 BUILTIN_STASH_CLEAR_USAGE
,
121 static const char * const git_stash_store_usage
[] = {
122 BUILTIN_STASH_STORE_USAGE
,
126 static const char * const git_stash_push_usage
[] = {
127 BUILTIN_STASH_PUSH_USAGE
,
131 static const char * const git_stash_save_usage
[] = {
132 BUILTIN_STASH_SAVE_USAGE
,
136 static const char * const git_stash_export_usage
[] = {
137 BUILTIN_STASH_EXPORT_USAGE
,
141 static const char * const git_stash_import_usage
[] = {
142 BUILTIN_STASH_IMPORT_USAGE
,
146 static const char ref_stash
[] = "refs/stash";
147 static struct strbuf stash_index_path
= STRBUF_INIT
;
150 * w_commit is set to the commit containing the working tree
151 * b_commit is set to the base commit
152 * i_commit is set to the commit containing the index tree
153 * u_commit is set to the commit containing the untracked files tree
154 * c_commit is set to the first parent (chain commit) when importing and is otherwise unset
155 * w_tree is set to the working tree
156 * b_tree is set to the base tree
157 * i_tree is set to the index tree
158 * u_tree is set to the untracked files tree
161 struct object_id w_commit
;
162 struct object_id b_commit
;
163 struct object_id i_commit
;
164 struct object_id u_commit
;
165 struct object_id c_commit
;
166 struct object_id w_tree
;
167 struct object_id b_tree
;
168 struct object_id i_tree
;
169 struct object_id u_tree
;
170 struct strbuf revision
;
175 #define STASH_INFO_INIT { \
176 .revision = STRBUF_INIT, \
179 static void free_stash_info(struct stash_info
*info
)
181 strbuf_release(&info
->revision
);
184 static int check_stash_topology(struct repository
*r
, struct commit
*stash
)
186 struct commit
*p1
, *p2
, *p3
= NULL
;
188 /* stash must have two or three parents */
189 if (!stash
->parents
|| !stash
->parents
->next
||
190 (stash
->parents
->next
->next
&& stash
->parents
->next
->next
->next
))
192 p1
= stash
->parents
->item
;
193 p2
= stash
->parents
->next
->item
;
194 if (stash
->parents
->next
->next
)
195 p3
= stash
->parents
->next
->next
->item
;
196 if (repo_parse_commit(r
, p1
) || repo_parse_commit(r
, p2
) ||
197 (p3
&& repo_parse_commit(r
, p3
)))
199 /* p2 must have a single parent, p3 must have no parents */
200 if (!p2
->parents
|| p2
->parents
->next
|| (p3
&& p3
->parents
))
202 if (repo_parse_commit(r
, p2
->parents
->item
))
204 /* p2^1 must equal p1 */
205 if (!oideq(&p1
->object
.oid
, &p2
->parents
->item
->object
.oid
))
211 static void assert_stash_like(struct stash_info
*info
, const char *revision
)
213 if (get_oidf(&info
->b_commit
, "%s^1", revision
) ||
214 get_oidf(&info
->w_tree
, "%s:", revision
) ||
215 get_oidf(&info
->b_tree
, "%s^1:", revision
) ||
216 get_oidf(&info
->i_tree
, "%s^2:", revision
))
217 die(_("'%s' is not a stash-like commit"), revision
);
220 static int parse_stash_revision(struct strbuf
*revision
, const char *commit
, int quiet
)
222 strbuf_reset(revision
);
224 if (!refs_ref_exists(get_main_ref_store(the_repository
), ref_stash
)) {
226 fprintf_ln(stderr
, _("No stash entries found."));
230 strbuf_addf(revision
, "%s@{0}", ref_stash
);
231 } else if (strspn(commit
, "0123456789") == strlen(commit
)) {
232 strbuf_addf(revision
, "%s@{%s}", ref_stash
, commit
);
234 strbuf_addstr(revision
, commit
);
239 static int get_stash_info(struct stash_info
*info
, int argc
, const char **argv
)
244 const char *revision
;
245 const char *commit
= NULL
;
246 struct object_id dummy
;
247 struct strbuf symbolic
= STRBUF_INIT
;
251 struct strbuf refs_msg
= STRBUF_INIT
;
253 for (i
= 0; i
< argc
; i
++)
254 strbuf_addf(&refs_msg
, " '%s'", argv
[i
]);
256 fprintf_ln(stderr
, _("Too many revisions specified:%s"),
258 strbuf_release(&refs_msg
);
266 strbuf_init(&info
->revision
, 0);
267 if (parse_stash_revision(&info
->revision
, commit
, 0)) {
271 revision
= info
->revision
.buf
;
273 if (repo_get_oid(the_repository
, revision
, &info
->w_commit
))
274 return error(_("%s is not a valid reference"), revision
);
276 assert_stash_like(info
, revision
);
278 info
->has_u
= !get_oidf(&info
->u_tree
, "%s^3:", revision
);
280 end_of_rev
= strchrnul(revision
, '@');
281 strbuf_add(&symbolic
, revision
, end_of_rev
- revision
);
283 ret
= repo_dwim_ref(the_repository
, symbolic
.buf
, symbolic
.len
,
284 &dummy
, &expanded_ref
, 0);
285 strbuf_release(&symbolic
);
287 case 0: /* Not found, but valid ref */
288 info
->is_stash_ref
= 0;
291 info
->is_stash_ref
= !strcmp(expanded_ref
, ref_stash
);
293 default: /* Invalid or ambiguous */
298 return !(ret
== 0 || ret
== 1);
301 static int do_clear_stash(void)
303 struct object_id obj
;
304 if (repo_get_oid(the_repository
, ref_stash
, &obj
))
307 return refs_delete_ref(get_main_ref_store(the_repository
), NULL
,
311 static int clear_stash(int argc
, const char **argv
, const char *prefix
,
312 struct repository
*repo UNUSED
)
314 struct option options
[] = {
318 argc
= parse_options(argc
, argv
, prefix
, options
,
319 git_stash_clear_usage
,
320 PARSE_OPT_STOP_AT_NON_OPTION
);
323 return error(_("git stash clear with arguments is "
326 return do_clear_stash();
329 static int reset_tree(struct object_id
*i_tree
, int update
, int reset
)
332 struct unpack_trees_options opts
;
333 struct tree_desc t
[MAX_UNPACK_TREES
];
335 struct lock_file lock_file
= LOCK_INIT
;
337 repo_read_index_preload(the_repository
, NULL
, 0);
338 if (refresh_index(the_repository
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
))
341 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
343 memset(&opts
, 0, sizeof(opts
));
345 tree
= parse_tree_indirect(i_tree
);
346 if (parse_tree(tree
))
349 init_tree_desc(t
, &tree
->object
.oid
, tree
->buffer
, tree
->size
);
352 opts
.src_index
= the_repository
->index
;
353 opts
.dst_index
= the_repository
->index
;
355 opts
.reset
= reset
? UNPACK_RESET_PROTECT_UNTRACKED
: 0;
356 opts
.update
= update
;
358 opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
359 opts
.fn
= oneway_merge
;
361 if (unpack_trees(nr_trees
, t
, &opts
))
364 if (write_locked_index(the_repository
->index
, &lock_file
, COMMIT_LOCK
))
365 return error(_("unable to write new index file"));
370 static int diff_tree_binary(struct strbuf
*out
, struct object_id
*w_commit
)
372 struct child_process cp
= CHILD_PROCESS_INIT
;
373 const char *w_commit_hex
= oid_to_hex(w_commit
);
376 * Diff-tree would not be very hard to replace with a native function,
377 * however it should be done together with apply_cached.
380 strvec_pushl(&cp
.args
, "diff-tree", "--binary", NULL
);
381 strvec_pushf(&cp
.args
, "%s^2^..%s^2", w_commit_hex
, w_commit_hex
);
383 return pipe_command(&cp
, NULL
, 0, out
, 0, NULL
, 0);
386 static int apply_cached(struct strbuf
*out
)
388 struct child_process cp
= CHILD_PROCESS_INIT
;
391 * Apply currently only reads either from stdin or a file, thus
392 * apply_all_patches would have to be updated to optionally take a
396 strvec_pushl(&cp
.args
, "apply", "--cached", NULL
);
397 return pipe_command(&cp
, out
->buf
, out
->len
, NULL
, 0, NULL
, 0);
400 static int reset_head(void)
402 struct child_process cp
= CHILD_PROCESS_INIT
;
405 * Reset is overall quite simple, however there is no current public
409 strvec_pushl(&cp
.args
, "reset", "--quiet", "--refresh", NULL
);
411 return run_command(&cp
);
414 static int is_path_a_directory(const char *path
)
417 * This function differs from abspath.c:is_directory() in that
418 * here we use lstat() instead of stat(); we do not want to
419 * follow symbolic links here.
422 return (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
));
425 static void add_diff_to_buf(struct diff_queue_struct
*q
,
426 struct diff_options
*options UNUSED
,
431 for (i
= 0; i
< q
->nr
; i
++) {
432 if (is_path_a_directory(q
->queue
[i
]->one
->path
))
435 strbuf_addstr(data
, q
->queue
[i
]->one
->path
);
437 /* NUL-terminate: will be fed to update-index -z */
438 strbuf_addch(data
, '\0');
442 static int restore_untracked(struct object_id
*u_tree
)
445 struct child_process cp
= CHILD_PROCESS_INIT
;
448 * We need to run restore files from a given index, but without
449 * affecting the current index, so we use GIT_INDEX_FILE with
450 * run_command to fork processes that will not interfere.
453 strvec_push(&cp
.args
, "read-tree");
454 strvec_push(&cp
.args
, oid_to_hex(u_tree
));
455 strvec_pushf(&cp
.env
, "GIT_INDEX_FILE=%s",
456 stash_index_path
.buf
);
457 if (run_command(&cp
)) {
458 remove_path(stash_index_path
.buf
);
462 child_process_init(&cp
);
464 strvec_pushl(&cp
.args
, "checkout-index", "--all", NULL
);
465 strvec_pushf(&cp
.env
, "GIT_INDEX_FILE=%s",
466 stash_index_path
.buf
);
468 res
= run_command(&cp
);
469 remove_path(stash_index_path
.buf
);
473 static void unstage_changes_unless_new(struct object_id
*orig_tree
)
476 * When we enter this function, there has been a clean merge of
477 * relevant trees, and the merge logic always stages whatever merges
478 * cleanly. We want to unstage those changes, unless it corresponds
479 * to a file that didn't exist as of orig_tree.
481 * However, if any SKIP_WORKTREE path is modified relative to
482 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
483 * it to the worktree before unstaging.
486 struct checkout state
= CHECKOUT_INIT
;
487 struct diff_options diff_opts
;
488 struct lock_file lock
= LOCK_INIT
;
491 /* If any entries have skip_worktree set, we'll have to check 'em out */
494 state
.refresh_cache
= 1;
495 state
.istate
= the_repository
->index
;
498 * Step 1: get a difference between orig_tree (which corresponding
499 * to the index before a merge was run) and the current index
500 * (reflecting the changes brought in by the merge).
502 repo_diff_setup(the_repository
, &diff_opts
);
503 diff_opts
.flags
.recursive
= 1;
504 diff_opts
.detect_rename
= 0;
505 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
506 diff_setup_done(&diff_opts
);
508 do_diff_cache(orig_tree
, &diff_opts
);
509 diffcore_std(&diff_opts
);
511 /* Iterate over the paths that changed due to the merge... */
512 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
513 struct diff_filepair
*p
;
514 struct cache_entry
*ce
;
517 /* Look up the path's position in the current index. */
518 p
= diff_queued_diff
.queue
[i
];
519 pos
= index_name_pos(the_repository
->index
, p
->two
->path
,
520 strlen(p
->two
->path
));
523 * Step 2: Place changes in the working tree
525 * Stash is about restoring changes *to the working tree*.
526 * So if the merge successfully got a new version of some
527 * path, but left it out of the working tree, then clear the
528 * SKIP_WORKTREE bit and write it to the working tree.
530 if (pos
>= 0 && ce_skip_worktree(the_repository
->index
->cache
[pos
])) {
533 ce
= the_repository
->index
->cache
[pos
];
534 if (!lstat(ce
->name
, &st
)) {
535 /* Conflicting path present; relocate it */
536 struct strbuf new_path
= STRBUF_INIT
;
539 strbuf_addf(&new_path
,
540 "%s.stash.XXXXXX", ce
->name
);
541 fd
= xmkstemp(new_path
.buf
);
543 printf(_("WARNING: Untracked file in way of "
544 "tracked file! Renaming\n "
547 ce
->name
, new_path
.buf
);
548 if (rename(ce
->name
, new_path
.buf
))
549 die("Failed to move %s to %s",
550 ce
->name
, new_path
.buf
);
551 strbuf_release(&new_path
);
553 checkout_entry(ce
, &state
, NULL
, NULL
);
554 ce
->ce_flags
&= ~CE_SKIP_WORKTREE
;
558 * Step 3: "unstage" changes, as long as they are still tracked
560 if (p
->one
->oid_valid
) {
562 * Path existed in orig_tree; restore index entry
563 * from that tree in order to "unstage" the changes.
565 int option
= ADD_CACHE_OK_TO_REPLACE
;
567 option
= ADD_CACHE_OK_TO_ADD
;
569 ce
= make_cache_entry(the_repository
->index
,
574 add_index_entry(the_repository
->index
, ce
, option
);
577 diff_flush(&diff_opts
);
580 * Step 4: write the new index to disk
582 repo_hold_locked_index(the_repository
, &lock
, LOCK_DIE_ON_ERROR
);
583 if (write_locked_index(the_repository
->index
, &lock
,
584 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
585 die(_("could not write index"));
588 static int do_apply_stash(const char *prefix
, struct stash_info
*info
,
589 int index
, int quiet
)
592 int has_index
= index
;
593 struct merge_options o
;
594 struct object_id c_tree
;
595 struct object_id index_tree
;
596 struct tree
*head
, *merge
, *merge_base
;
597 struct lock_file lock
= LOCK_INIT
;
599 repo_read_index_preload(the_repository
, NULL
, 0);
600 if (repo_refresh_and_write_index(the_repository
, REFRESH_QUIET
, 0, 0,
602 return error(_("could not write index"));
604 if (write_index_as_tree(&c_tree
, the_repository
->index
,
605 repo_get_index_file(the_repository
), 0, NULL
))
606 return error(_("cannot apply a stash in the middle of a merge"));
609 if (oideq(&info
->b_tree
, &info
->i_tree
) ||
610 oideq(&c_tree
, &info
->i_tree
)) {
613 struct strbuf out
= STRBUF_INIT
;
615 if (diff_tree_binary(&out
, &info
->w_commit
)) {
616 strbuf_release(&out
);
617 return error(_("could not generate diff %s^!."),
618 oid_to_hex(&info
->w_commit
));
621 ret
= apply_cached(&out
);
622 strbuf_release(&out
);
624 return error(_("conflicts in index. "
625 "Try without --index."));
627 discard_index(the_repository
->index
);
628 repo_read_index(the_repository
);
629 if (write_index_as_tree(&index_tree
, the_repository
->index
,
630 repo_get_index_file(the_repository
), 0, NULL
))
631 return error(_("could not save index tree"));
634 discard_index(the_repository
->index
);
635 repo_read_index(the_repository
);
639 init_ui_merge_options(&o
, the_repository
);
641 o
.branch1
= "Updated upstream";
642 o
.branch2
= "Stashed changes";
643 o
.ancestor
= "Stash base";
645 if (oideq(&info
->b_tree
, &c_tree
))
646 o
.branch1
= "Version stash was based on";
651 if (o
.verbosity
>= 3)
652 printf_ln(_("Merging %s with %s"), o
.branch1
, o
.branch2
);
654 head
= lookup_tree(o
.repo
, &c_tree
);
655 merge
= lookup_tree(o
.repo
, &info
->w_tree
);
656 merge_base
= lookup_tree(o
.repo
, &info
->b_tree
);
658 repo_hold_locked_index(o
.repo
, &lock
, LOCK_DIE_ON_ERROR
);
659 clean
= merge_ort_nonrecursive(&o
, head
, merge
, merge_base
);
662 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
663 * merge was clean, and nonzero if the merge was unclean or encountered
666 ret
= clean
>= 0 ? !clean
: clean
;
669 rollback_lock_file(&lock
);
670 else if (write_locked_index(o
.repo
->index
, &lock
,
671 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
672 ret
= error(_("could not write index"));
675 repo_rerere(the_repository
, 0);
678 fprintf_ln(stderr
, _("Index was not unstashed."));
680 goto restore_untracked
;
684 if (reset_tree(&index_tree
, 0, 0))
687 unstage_changes_unless_new(&c_tree
);
691 if (info
->has_u
&& restore_untracked(&info
->u_tree
))
692 ret
= error(_("could not restore untracked files from stash"));
695 struct child_process cp
= CHILD_PROCESS_INIT
;
698 * Status is quite simple and could be replaced with calls to
699 * wt_status in the future, but it adds complexities which may
700 * require more tests.
704 strvec_pushf(&cp
.env
, GIT_WORK_TREE_ENVIRONMENT
"=%s",
705 absolute_path(repo_get_work_tree(the_repository
)));
706 strvec_pushf(&cp
.env
, GIT_DIR_ENVIRONMENT
"=%s",
707 absolute_path(repo_get_git_dir(the_repository
)));
708 strvec_push(&cp
.args
, "status");
715 static int apply_stash(int argc
, const char **argv
, const char *prefix
,
716 struct repository
*repo UNUSED
)
721 struct stash_info info
= STASH_INFO_INIT
;
722 struct option options
[] = {
723 OPT__QUIET(&quiet
, N_("be quiet, only report errors")),
724 OPT_BOOL(0, "index", &index
,
725 N_("attempt to recreate the index")),
729 argc
= parse_options(argc
, argv
, prefix
, options
,
730 git_stash_apply_usage
, 0);
732 if (get_stash_info(&info
, argc
, argv
))
735 ret
= do_apply_stash(prefix
, &info
, index
, quiet
);
737 free_stash_info(&info
);
741 static int reject_reflog_ent(struct object_id
*ooid UNUSED
,
742 struct object_id
*noid UNUSED
,
743 const char *email UNUSED
,
744 timestamp_t timestamp UNUSED
,
745 int tz UNUSED
, const char *message UNUSED
,
746 void *cb_data UNUSED
)
751 static int reflog_is_empty(const char *refname
)
753 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository
),
754 refname
, reject_reflog_ent
, NULL
);
757 static int do_drop_stash(struct stash_info
*info
, int quiet
)
759 if (!reflog_delete(info
->revision
.buf
,
760 EXPIRE_REFLOGS_REWRITE
| EXPIRE_REFLOGS_UPDATE_REF
,
763 printf_ln(_("Dropped %s (%s)"), info
->revision
.buf
,
764 oid_to_hex(&info
->w_commit
));
766 return error(_("%s: Could not drop stash entry"),
770 if (reflog_is_empty(ref_stash
))
776 static int get_stash_info_assert(struct stash_info
*info
, int argc
,
779 int ret
= get_stash_info(info
, argc
, argv
);
784 if (!info
->is_stash_ref
)
785 return error(_("'%s' is not a stash reference"), info
->revision
.buf
);
790 static int drop_stash(int argc
, const char **argv
, const char *prefix
,
791 struct repository
*repo UNUSED
)
795 struct stash_info info
= STASH_INFO_INIT
;
796 struct option options
[] = {
797 OPT__QUIET(&quiet
, N_("be quiet, only report errors")),
801 argc
= parse_options(argc
, argv
, prefix
, options
,
802 git_stash_drop_usage
, 0);
804 if (get_stash_info_assert(&info
, argc
, argv
))
807 ret
= do_drop_stash(&info
, quiet
);
809 free_stash_info(&info
);
813 static int pop_stash(int argc
, const char **argv
, const char *prefix
,
814 struct repository
*repo UNUSED
)
819 struct stash_info info
= STASH_INFO_INIT
;
820 struct option options
[] = {
821 OPT__QUIET(&quiet
, N_("be quiet, only report errors")),
822 OPT_BOOL(0, "index", &index
,
823 N_("attempt to recreate the index")),
827 argc
= parse_options(argc
, argv
, prefix
, options
,
828 git_stash_pop_usage
, 0);
830 if (get_stash_info_assert(&info
, argc
, argv
))
833 if ((ret
= do_apply_stash(prefix
, &info
, index
, quiet
)))
834 printf_ln(_("The stash entry is kept in case "
835 "you need it again."));
837 ret
= do_drop_stash(&info
, quiet
);
840 free_stash_info(&info
);
844 static int branch_stash(int argc
, const char **argv
, const char *prefix
,
845 struct repository
*repo UNUSED
)
848 const char *branch
= NULL
;
849 struct stash_info info
= STASH_INFO_INIT
;
850 struct child_process cp
= CHILD_PROCESS_INIT
;
851 struct option options
[] = {
855 argc
= parse_options(argc
, argv
, prefix
, options
,
856 git_stash_branch_usage
, 0);
859 fprintf_ln(stderr
, _("No branch name specified"));
865 if (get_stash_info(&info
, argc
- 1, argv
+ 1))
869 strvec_pushl(&cp
.args
, "checkout", "-b", NULL
);
870 strvec_push(&cp
.args
, branch
);
871 strvec_push(&cp
.args
, oid_to_hex(&info
.b_commit
));
872 ret
= run_command(&cp
);
874 ret
= do_apply_stash(prefix
, &info
, 1, 0);
875 if (!ret
&& info
.is_stash_ref
)
876 ret
= do_drop_stash(&info
, 0);
879 free_stash_info(&info
);
883 static int list_stash(int argc
, const char **argv
, const char *prefix
,
884 struct repository
*repo UNUSED
)
886 struct child_process cp
= CHILD_PROCESS_INIT
;
887 struct option options
[] = {
891 argc
= parse_options(argc
, argv
, prefix
, options
,
892 git_stash_list_usage
,
893 PARSE_OPT_KEEP_UNKNOWN_OPT
);
895 if (!refs_ref_exists(get_main_ref_store(the_repository
), ref_stash
))
899 strvec_pushl(&cp
.args
, "log", "--format=%gd: %gs", "-g",
900 "--first-parent", NULL
);
901 strvec_pushv(&cp
.args
, argv
);
902 strvec_push(&cp
.args
, ref_stash
);
903 strvec_push(&cp
.args
, "--");
904 return run_command(&cp
);
907 static int show_stat
= 1;
908 static int show_patch
;
909 static int show_include_untracked
;
911 static int git_stash_config(const char *var
, const char *value
,
912 const struct config_context
*ctx
, void *cb
)
914 if (!strcmp(var
, "stash.showstat")) {
915 show_stat
= git_config_bool(var
, value
);
918 if (!strcmp(var
, "stash.showpatch")) {
919 show_patch
= git_config_bool(var
, value
);
922 if (!strcmp(var
, "stash.showincludeuntracked")) {
923 show_include_untracked
= git_config_bool(var
, value
);
926 return git_diff_basic_config(var
, value
, ctx
, cb
);
929 static void diff_include_untracked(const struct stash_info
*info
, struct diff_options
*diff_opt
)
931 const struct object_id
*oid
[] = { &info
->w_commit
, &info
->u_tree
};
932 struct tree
*tree
[ARRAY_SIZE(oid
)];
933 struct tree_desc tree_desc
[ARRAY_SIZE(oid
)];
934 struct unpack_trees_options unpack_tree_opt
= { 0 };
936 for (size_t i
= 0; i
< ARRAY_SIZE(oid
); i
++) {
937 tree
[i
] = parse_tree_indirect(oid
[i
]);
938 if (parse_tree(tree
[i
]) < 0)
939 die(_("failed to parse tree"));
940 init_tree_desc(&tree_desc
[i
], &tree
[i
]->object
.oid
,
941 tree
[i
]->buffer
, tree
[i
]->size
);
944 unpack_tree_opt
.head_idx
= -1;
945 unpack_tree_opt
.src_index
= the_repository
->index
;
946 unpack_tree_opt
.dst_index
= the_repository
->index
;
947 unpack_tree_opt
.merge
= 1;
948 unpack_tree_opt
.fn
= stash_worktree_untracked_merge
;
950 if (unpack_trees(ARRAY_SIZE(tree_desc
), tree_desc
, &unpack_tree_opt
))
951 die(_("failed to unpack trees"));
953 do_diff_cache(&info
->b_commit
, diff_opt
);
956 static int show_stash(int argc
, const char **argv
, const char *prefix
,
957 struct repository
*repo UNUSED
)
961 struct stash_info info
= STASH_INFO_INIT
;
963 struct strvec stash_args
= STRVEC_INIT
;
964 struct strvec revision_args
= STRVEC_INIT
;
969 } show_untracked
= show_include_untracked
? UNTRACKED_INCLUDE
: UNTRACKED_NONE
;
970 struct option options
[] = {
971 OPT_SET_INT('u', "include-untracked", &show_untracked
,
972 N_("include untracked files in the stash"),
974 OPT_SET_INT_F(0, "only-untracked", &show_untracked
,
975 N_("only show untracked files in the stash"),
976 UNTRACKED_ONLY
, PARSE_OPT_NONEG
),
981 init_diff_ui_defaults();
982 git_config(git_diff_ui_config
, NULL
);
983 repo_init_revisions(the_repository
, &rev
, prefix
);
985 argc
= parse_options(argc
, argv
, prefix
, options
, git_stash_show_usage
,
986 PARSE_OPT_KEEP_ARGV0
| PARSE_OPT_KEEP_UNKNOWN_OPT
|
987 PARSE_OPT_KEEP_DASHDASH
);
989 strvec_push(&revision_args
, argv
[0]);
990 for (i
= 1; i
< argc
; i
++) {
991 if (argv
[i
][0] != '-')
992 strvec_push(&stash_args
, argv
[i
]);
994 strvec_push(&revision_args
, argv
[i
]);
997 if (get_stash_info(&info
, stash_args
.nr
, stash_args
.v
))
1001 * The config settings are applied only if there are not passed
1004 if (revision_args
.nr
== 1) {
1006 rev
.diffopt
.output_format
= DIFF_FORMAT_DIFFSTAT
;
1009 rev
.diffopt
.output_format
|= DIFF_FORMAT_PATCH
;
1011 if (!show_stat
&& !show_patch
) {
1017 argc
= setup_revisions(revision_args
.nr
, revision_args
.v
, &rev
, NULL
);
1020 if (!rev
.diffopt
.output_format
) {
1021 rev
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1022 diff_setup_done(&rev
.diffopt
);
1025 rev
.diffopt
.flags
.recursive
= 1;
1026 setup_diff_pager(&rev
.diffopt
);
1027 switch (show_untracked
) {
1028 case UNTRACKED_NONE
:
1029 diff_tree_oid(&info
.b_commit
, &info
.w_commit
, "", &rev
.diffopt
);
1031 case UNTRACKED_ONLY
:
1033 diff_root_tree_oid(&info
.u_tree
, "", &rev
.diffopt
);
1035 case UNTRACKED_INCLUDE
:
1037 diff_include_untracked(&info
, &rev
.diffopt
);
1039 diff_tree_oid(&info
.b_commit
, &info
.w_commit
, "", &rev
.diffopt
);
1042 log_tree_diff_flush(&rev
);
1044 ret
= diff_result_code(&rev
);
1047 strvec_clear(&revision_args
);
1048 strvec_clear(&stash_args
);
1049 free_stash_info(&info
);
1050 release_revisions(&rev
);
1052 usage_with_options(git_stash_show_usage
, options
);
1059 static int do_store_stash(const struct object_id
*w_commit
, const char *stash_msg
,
1062 struct stash_info info
;
1063 char revision
[GIT_MAX_HEXSZ
];
1065 oid_to_hex_r(revision
, w_commit
);
1066 assert_stash_like(&info
, revision
);
1069 stash_msg
= "Created via \"git stash store\".";
1071 if (refs_update_ref(get_main_ref_store(the_repository
), stash_msg
, ref_stash
, w_commit
, NULL
,
1072 REF_FORCE_CREATE_REFLOG
,
1073 quiet
? UPDATE_REFS_QUIET_ON_ERR
:
1074 UPDATE_REFS_MSG_ON_ERR
)) {
1076 fprintf_ln(stderr
, _("Cannot update %s with %s"),
1077 ref_stash
, oid_to_hex(w_commit
));
1085 static int store_stash(int argc
, const char **argv
, const char *prefix
,
1086 struct repository
*repo UNUSED
)
1089 const char *stash_msg
= NULL
;
1090 struct object_id obj
;
1091 struct object_context dummy
= {0};
1092 struct option options
[] = {
1093 OPT__QUIET(&quiet
, N_("be quiet")),
1094 OPT_STRING('m', "message", &stash_msg
, "message",
1095 N_("stash message")),
1100 argc
= parse_options(argc
, argv
, prefix
, options
,
1101 git_stash_store_usage
,
1102 PARSE_OPT_KEEP_UNKNOWN_OPT
);
1106 fprintf_ln(stderr
, _("\"git stash store\" requires one "
1107 "<commit> argument"));
1111 if (get_oid_with_context(the_repository
,
1112 argv
[0], quiet
? GET_OID_QUIETLY
: 0, &obj
,
1115 fprintf_ln(stderr
, _("Cannot update %s with %s"),
1116 ref_stash
, argv
[0]);
1121 ret
= do_store_stash(&obj
, stash_msg
, quiet
);
1124 object_context_release(&dummy
);
1128 static void add_pathspecs(struct strvec
*args
,
1129 const struct pathspec
*ps
) {
1132 for (i
= 0; i
< ps
->nr
; i
++)
1133 strvec_push(args
, ps
->items
[i
].original
);
1137 * `untracked_files` will be filled with the names of untracked files.
1138 * The return value is:
1140 * = 0 if there are not any untracked files
1141 * > 0 if there are untracked files
1143 static int get_untracked_files(const struct pathspec
*ps
, int include_untracked
,
1144 struct strbuf
*untracked_files
)
1148 struct dir_struct dir
= DIR_INIT
;
1150 if (include_untracked
!= INCLUDE_ALL_FILES
)
1151 setup_standard_excludes(&dir
);
1153 fill_directory(&dir
, the_repository
->index
, ps
);
1154 for (i
= 0; i
< dir
.nr
; i
++) {
1155 struct dir_entry
*ent
= dir
.entries
[i
];
1157 strbuf_addstr(untracked_files
, ent
->name
);
1158 /* NUL-terminate: will be fed to update-index -z */
1159 strbuf_addch(untracked_files
, '\0');
1167 * The return value of `check_changes_tracked_files()` can be:
1169 * < 0 if there was an error
1170 * = 0 if there are no changes.
1171 * > 0 if there are changes.
1173 static int check_changes_tracked_files(const struct pathspec
*ps
)
1175 struct rev_info rev
;
1176 struct object_id dummy
;
1179 /* No initial commit. */
1180 if (repo_get_oid(the_repository
, "HEAD", &dummy
))
1183 if (repo_read_index(the_repository
) < 0)
1186 repo_init_revisions(the_repository
, &rev
, NULL
);
1187 copy_pathspec(&rev
.prune_data
, ps
);
1189 rev
.diffopt
.flags
.quick
= 1;
1190 rev
.diffopt
.flags
.ignore_submodules
= 1;
1193 add_head_to_pending(&rev
);
1194 diff_setup_done(&rev
.diffopt
);
1196 run_diff_index(&rev
, DIFF_INDEX_CACHED
);
1197 if (diff_result_code(&rev
)) {
1202 run_diff_files(&rev
, 0);
1203 if (diff_result_code(&rev
)) {
1209 release_revisions(&rev
);
1214 * The function will fill `untracked_files` with the names of untracked files
1215 * It will return 1 if there were any changes and 0 if there were not.
1217 static int check_changes(const struct pathspec
*ps
, int include_untracked
,
1218 struct strbuf
*untracked_files
)
1221 if (check_changes_tracked_files(ps
))
1224 if (include_untracked
&& get_untracked_files(ps
, include_untracked
,
1231 static int save_untracked_files(struct stash_info
*info
, struct strbuf
*msg
,
1232 struct strbuf files
)
1235 struct strbuf untracked_msg
= STRBUF_INIT
;
1236 struct child_process cp_upd_index
= CHILD_PROCESS_INIT
;
1237 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1239 cp_upd_index
.git_cmd
= 1;
1240 strvec_pushl(&cp_upd_index
.args
, "update-index", "-z", "--add",
1241 "--remove", "--stdin", NULL
);
1242 strvec_pushf(&cp_upd_index
.env
, "GIT_INDEX_FILE=%s",
1243 stash_index_path
.buf
);
1245 strbuf_addf(&untracked_msg
, "untracked files on %s\n", msg
->buf
);
1246 if (pipe_command(&cp_upd_index
, files
.buf
, files
.len
, NULL
, 0,
1252 if (write_index_as_tree(&info
->u_tree
, &istate
, stash_index_path
.buf
, 0,
1258 if (commit_tree(untracked_msg
.buf
, untracked_msg
.len
,
1259 &info
->u_tree
, NULL
, &info
->u_commit
, NULL
, NULL
)) {
1265 release_index(&istate
);
1266 strbuf_release(&untracked_msg
);
1267 remove_path(stash_index_path
.buf
);
1271 static int stash_staged(struct stash_info
*info
, struct strbuf
*out_patch
,
1275 struct child_process cp_diff_tree
= CHILD_PROCESS_INIT
;
1276 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1278 if (write_index_as_tree(&info
->w_tree
, &istate
, the_repository
->index_file
,
1284 cp_diff_tree
.git_cmd
= 1;
1285 strvec_pushl(&cp_diff_tree
.args
, "diff-tree", "-p", "--binary",
1286 "-U1", "HEAD", oid_to_hex(&info
->w_tree
), "--", NULL
);
1287 if (pipe_command(&cp_diff_tree
, NULL
, 0, out_patch
, 0, NULL
, 0)) {
1292 if (!out_patch
->len
) {
1294 fprintf_ln(stderr
, _("No staged changes"));
1299 release_index(&istate
);
1303 static int stash_patch(struct stash_info
*info
, const struct pathspec
*ps
,
1304 struct strbuf
*out_patch
, int quiet
)
1307 struct child_process cp_read_tree
= CHILD_PROCESS_INIT
;
1308 struct child_process cp_diff_tree
= CHILD_PROCESS_INIT
;
1309 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1310 char *old_index_env
= NULL
, *old_repo_index_file
;
1312 remove_path(stash_index_path
.buf
);
1314 cp_read_tree
.git_cmd
= 1;
1315 strvec_pushl(&cp_read_tree
.args
, "read-tree", "HEAD", NULL
);
1316 strvec_pushf(&cp_read_tree
.env
, "GIT_INDEX_FILE=%s",
1317 stash_index_path
.buf
);
1318 if (run_command(&cp_read_tree
)) {
1323 /* Find out what the user wants. */
1324 old_repo_index_file
= the_repository
->index_file
;
1325 the_repository
->index_file
= stash_index_path
.buf
;
1326 old_index_env
= xstrdup_or_null(getenv(INDEX_ENVIRONMENT
));
1327 setenv(INDEX_ENVIRONMENT
, the_repository
->index_file
, 1);
1329 ret
= !!run_add_p(the_repository
, ADD_P_STASH
, NULL
, ps
);
1331 the_repository
->index_file
= old_repo_index_file
;
1332 if (old_index_env
&& *old_index_env
)
1333 setenv(INDEX_ENVIRONMENT
, old_index_env
, 1);
1335 unsetenv(INDEX_ENVIRONMENT
);
1336 FREE_AND_NULL(old_index_env
);
1338 /* State of the working tree. */
1339 if (write_index_as_tree(&info
->w_tree
, &istate
, stash_index_path
.buf
, 0,
1345 cp_diff_tree
.git_cmd
= 1;
1346 strvec_pushl(&cp_diff_tree
.args
, "diff-tree", "-p", "-U1", "HEAD",
1347 oid_to_hex(&info
->w_tree
), "--", NULL
);
1348 if (pipe_command(&cp_diff_tree
, NULL
, 0, out_patch
, 0, NULL
, 0)) {
1353 if (!out_patch
->len
) {
1355 fprintf_ln(stderr
, _("No changes selected"));
1360 release_index(&istate
);
1361 remove_path(stash_index_path
.buf
);
1365 static int stash_working_tree(struct stash_info
*info
, const struct pathspec
*ps
)
1368 struct rev_info rev
;
1369 struct child_process cp_upd_index
= CHILD_PROCESS_INIT
;
1370 struct strbuf diff_output
= STRBUF_INIT
;
1371 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1373 repo_init_revisions(the_repository
, &rev
, NULL
);
1374 copy_pathspec(&rev
.prune_data
, ps
);
1376 set_alternate_index_output(stash_index_path
.buf
);
1377 if (reset_tree(&info
->i_tree
, 0, 0)) {
1381 set_alternate_index_output(NULL
);
1383 rev
.diffopt
.output_format
= DIFF_FORMAT_CALLBACK
;
1384 rev
.diffopt
.format_callback
= add_diff_to_buf
;
1385 rev
.diffopt
.format_callback_data
= &diff_output
;
1387 if (repo_read_index_preload(the_repository
, &rev
.diffopt
.pathspec
, 0) < 0) {
1392 add_pending_object(&rev
, parse_object(the_repository
, &info
->b_commit
),
1394 run_diff_index(&rev
, 0);
1396 cp_upd_index
.git_cmd
= 1;
1397 strvec_pushl(&cp_upd_index
.args
, "update-index",
1398 "--ignore-skip-worktree-entries",
1399 "-z", "--add", "--remove", "--stdin", NULL
);
1400 strvec_pushf(&cp_upd_index
.env
, "GIT_INDEX_FILE=%s",
1401 stash_index_path
.buf
);
1403 if (pipe_command(&cp_upd_index
, diff_output
.buf
, diff_output
.len
,
1404 NULL
, 0, NULL
, 0)) {
1409 if (write_index_as_tree(&info
->w_tree
, &istate
, stash_index_path
.buf
, 0,
1416 release_index(&istate
);
1417 release_revisions(&rev
);
1418 strbuf_release(&diff_output
);
1419 remove_path(stash_index_path
.buf
);
1423 static int do_create_stash(const struct pathspec
*ps
, struct strbuf
*stash_msg_buf
,
1424 int include_untracked
, int patch_mode
, int only_staged
,
1425 struct stash_info
*info
, struct strbuf
*patch
,
1430 int untracked_commit_option
= 0;
1431 const char *head_short_sha1
= NULL
;
1432 const char *branch_ref
= NULL
;
1433 const char *branch_name
= "(no branch)";
1434 char *branch_name_buf
= NULL
;
1435 struct commit
*head_commit
= NULL
;
1436 struct commit_list
*parents
= NULL
;
1437 struct strbuf msg
= STRBUF_INIT
;
1438 struct strbuf commit_tree_label
= STRBUF_INIT
;
1439 struct strbuf untracked_files
= STRBUF_INIT
;
1441 prepare_fallback_ident("git stash", "git@stash");
1443 repo_read_index_preload(the_repository
, NULL
, 0);
1444 if (repo_refresh_and_write_index(the_repository
, REFRESH_QUIET
, 0, 0,
1445 NULL
, NULL
, NULL
) < 0) {
1446 ret
= error(_("could not write index"));
1450 if (repo_get_oid(the_repository
, "HEAD", &info
->b_commit
)) {
1452 fprintf_ln(stderr
, _("You do not have "
1453 "the initial commit yet"));
1457 head_commit
= lookup_commit(the_repository
, &info
->b_commit
);
1460 if (!check_changes(ps
, include_untracked
, &untracked_files
)) {
1465 branch_ref
= refs_resolve_ref_unsafe(get_main_ref_store(the_repository
),
1466 "HEAD", 0, NULL
, &flags
);
1468 if (flags
& REF_ISSYMREF
) {
1469 if (skip_prefix(branch_ref
, "refs/heads/", &branch_name
))
1470 branch_name
= branch_name_buf
= xstrdup(branch_name
);
1473 head_short_sha1
= repo_find_unique_abbrev(the_repository
,
1474 &head_commit
->object
.oid
,
1476 strbuf_addf(&msg
, "%s: %s ", branch_name
, head_short_sha1
);
1477 pp_commit_easy(CMIT_FMT_ONELINE
, head_commit
, &msg
);
1479 strbuf_addf(&commit_tree_label
, "index on %s\n", msg
.buf
);
1480 commit_list_insert(head_commit
, &parents
);
1481 if (write_index_as_tree(&info
->i_tree
, the_repository
->index
,
1482 repo_get_index_file(the_repository
), 0, NULL
) ||
1483 commit_tree(commit_tree_label
.buf
, commit_tree_label
.len
,
1484 &info
->i_tree
, parents
, &info
->i_commit
, NULL
, NULL
)) {
1486 fprintf_ln(stderr
, _("Cannot save the current "
1492 free_commit_list(parents
);
1495 if (include_untracked
) {
1496 if (save_untracked_files(info
, &msg
, untracked_files
)) {
1498 fprintf_ln(stderr
, _("Cannot save "
1499 "the untracked files"));
1503 untracked_commit_option
= 1;
1506 ret
= stash_patch(info
, ps
, patch
, quiet
);
1509 fprintf_ln(stderr
, _("Cannot save the current "
1512 } else if (ret
> 0) {
1515 } else if (only_staged
) {
1516 ret
= stash_staged(info
, patch
, quiet
);
1519 fprintf_ln(stderr
, _("Cannot save the current "
1522 } else if (ret
> 0) {
1526 if (stash_working_tree(info
, ps
)) {
1528 fprintf_ln(stderr
, _("Cannot save the current "
1535 if (!stash_msg_buf
->len
)
1536 strbuf_addf(stash_msg_buf
, "WIP on %s", msg
.buf
);
1538 strbuf_insertf(stash_msg_buf
, 0, "On %s: ", branch_name
);
1540 if (untracked_commit_option
)
1541 commit_list_insert(lookup_commit(the_repository
,
1544 commit_list_insert(lookup_commit(the_repository
, &info
->i_commit
),
1546 commit_list_insert(head_commit
, &parents
);
1548 if (commit_tree(stash_msg_buf
->buf
, stash_msg_buf
->len
, &info
->w_tree
,
1549 parents
, &info
->w_commit
, NULL
, NULL
)) {
1551 fprintf_ln(stderr
, _("Cannot record "
1552 "working tree state"));
1558 strbuf_release(&commit_tree_label
);
1559 strbuf_release(&msg
);
1560 strbuf_release(&untracked_files
);
1561 free_commit_list(parents
);
1562 free(branch_name_buf
);
1566 static int create_stash(int argc
, const char **argv
, const char *prefix UNUSED
,
1567 struct repository
*repo UNUSED
)
1570 struct strbuf stash_msg_buf
= STRBUF_INIT
;
1571 struct stash_info info
= STASH_INFO_INIT
;
1574 /* Starting with argv[1], since argv[0] is "create" */
1575 strbuf_join_argv(&stash_msg_buf
, argc
- 1, ++argv
, ' ');
1577 memset(&ps
, 0, sizeof(ps
));
1578 if (!check_changes_tracked_files(&ps
))
1581 ret
= do_create_stash(&ps
, &stash_msg_buf
, 0, 0, 0, &info
,
1584 printf_ln("%s", oid_to_hex(&info
.w_commit
));
1586 free_stash_info(&info
);
1587 strbuf_release(&stash_msg_buf
);
1591 static int do_push_stash(const struct pathspec
*ps
, const char *stash_msg
, int quiet
,
1592 int keep_index
, int patch_mode
, int include_untracked
, int only_staged
)
1595 struct stash_info info
= STASH_INFO_INIT
;
1596 struct strbuf patch
= STRBUF_INIT
;
1597 struct strbuf stash_msg_buf
= STRBUF_INIT
;
1598 struct strbuf untracked_files
= STRBUF_INIT
;
1599 struct strbuf out
= STRBUF_INIT
;
1601 if (patch_mode
&& keep_index
== -1)
1604 if (patch_mode
&& include_untracked
) {
1605 fprintf_ln(stderr
, _("Can't use --patch and --include-untracked"
1606 " or --all at the same time"));
1611 /* --patch overrides --staged */
1615 if (only_staged
&& include_untracked
) {
1616 fprintf_ln(stderr
, _("Can't use --staged and --include-untracked"
1617 " or --all at the same time"));
1622 repo_read_index_preload(the_repository
, NULL
, 0);
1623 if (!include_untracked
&& ps
->nr
) {
1624 char *ps_matched
= xcalloc(ps
->nr
, 1);
1626 /* TODO: audit for interaction with sparse-index. */
1627 ensure_full_index(the_repository
->index
);
1628 for (size_t i
= 0; i
< the_repository
->index
->cache_nr
; i
++)
1629 ce_path_match(the_repository
->index
, the_repository
->index
->cache
[i
], ps
,
1632 if (report_path_error(ps_matched
, ps
)) {
1633 fprintf_ln(stderr
, _("Did you forget to 'git add'?"));
1641 if (repo_refresh_and_write_index(the_repository
, REFRESH_QUIET
, 0, 0,
1642 NULL
, NULL
, NULL
)) {
1643 ret
= error(_("could not write index"));
1647 if (!check_changes(ps
, include_untracked
, &untracked_files
)) {
1649 printf_ln(_("No local changes to save"));
1653 if (!refs_reflog_exists(get_main_ref_store(the_repository
), ref_stash
) && do_clear_stash()) {
1656 fprintf_ln(stderr
, _("Cannot initialize stash"));
1661 strbuf_addstr(&stash_msg_buf
, stash_msg
);
1662 if (do_create_stash(ps
, &stash_msg_buf
, include_untracked
, patch_mode
, only_staged
,
1663 &info
, &patch
, quiet
)) {
1668 if (do_store_stash(&info
.w_commit
, stash_msg_buf
.buf
, 1)) {
1671 fprintf_ln(stderr
, _("Cannot save the current status"));
1676 printf_ln(_("Saved working directory and index state %s"),
1679 if (!(patch_mode
|| only_staged
)) {
1680 if (include_untracked
&& !ps
->nr
) {
1681 struct child_process cp
= CHILD_PROCESS_INIT
;
1684 if (startup_info
->original_cwd
) {
1685 cp
.dir
= startup_info
->original_cwd
;
1686 strvec_pushf(&cp
.env
, "%s=%s",
1687 GIT_WORK_TREE_ENVIRONMENT
,
1688 the_repository
->worktree
);
1690 strvec_pushl(&cp
.args
, "clean", "--force",
1691 "--quiet", "-d", ":/", NULL
);
1692 if (include_untracked
== INCLUDE_ALL_FILES
)
1693 strvec_push(&cp
.args
, "-x");
1694 if (run_command(&cp
)) {
1699 discard_index(the_repository
->index
);
1701 struct child_process cp_add
= CHILD_PROCESS_INIT
;
1702 struct child_process cp_diff
= CHILD_PROCESS_INIT
;
1703 struct child_process cp_apply
= CHILD_PROCESS_INIT
;
1706 strvec_push(&cp_add
.args
, "add");
1707 if (!include_untracked
)
1708 strvec_push(&cp_add
.args
, "-u");
1709 if (include_untracked
== INCLUDE_ALL_FILES
)
1710 strvec_push(&cp_add
.args
, "--force");
1711 strvec_push(&cp_add
.args
, "--");
1712 add_pathspecs(&cp_add
.args
, ps
);
1713 if (run_command(&cp_add
)) {
1718 cp_diff
.git_cmd
= 1;
1719 strvec_pushl(&cp_diff
.args
, "diff-index", "-p",
1720 "--cached", "--binary", "HEAD", "--",
1722 add_pathspecs(&cp_diff
.args
, ps
);
1723 if (pipe_command(&cp_diff
, NULL
, 0, &out
, 0, NULL
, 0)) {
1728 cp_apply
.git_cmd
= 1;
1729 strvec_pushl(&cp_apply
.args
, "apply", "--index",
1731 if (pipe_command(&cp_apply
, out
.buf
, out
.len
, NULL
, 0,
1737 struct child_process cp
= CHILD_PROCESS_INIT
;
1739 /* BUG: this nukes untracked files in the way */
1740 strvec_pushl(&cp
.args
, "reset", "--hard", "-q",
1741 "--no-recurse-submodules", NULL
);
1742 if (run_command(&cp
)) {
1749 * When keeping staged entries, we need to reset the working
1750 * directory to match the state of our index. This can be
1751 * skipped when the index is the empty tree, because there is
1752 * nothing to reset in that case:
1754 * - When the index has any file, regardless of whether
1755 * staged or not, the tree cannot be empty by definition
1756 * and thus we enter the condition.
1758 * - When the index has no files, the only thing we need to
1759 * care about is untracked files when `--include-untracked`
1760 * is given. But as we already execute git-clean(1) further
1761 * up to delete such untracked files we don't have to do
1762 * anything here, either.
1764 * We thus skip calling git-checkout(1) in this case, also
1765 * because running it on an empty tree will cause it to fail
1766 * due to the pathspec not matching anything.
1768 if (keep_index
== 1 && !is_null_oid(&info
.i_tree
) &&
1769 !is_empty_tree_oid(&info
.i_tree
, the_repository
->hash_algo
)) {
1770 struct child_process cp
= CHILD_PROCESS_INIT
;
1773 strvec_pushl(&cp
.args
, "checkout", "--no-overlay",
1774 oid_to_hex(&info
.i_tree
), "--", NULL
);
1776 strvec_push(&cp
.args
, ":/");
1778 add_pathspecs(&cp
.args
, ps
);
1779 if (run_command(&cp
)) {
1786 struct child_process cp
= CHILD_PROCESS_INIT
;
1789 strvec_pushl(&cp
.args
, "apply", "-R", NULL
);
1791 if (pipe_command(&cp
, patch
.buf
, patch
.len
, NULL
, 0, NULL
, 0)) {
1793 fprintf_ln(stderr
, _("Cannot remove "
1794 "worktree changes"));
1799 if (keep_index
< 1) {
1800 struct child_process cp
= CHILD_PROCESS_INIT
;
1803 strvec_pushl(&cp
.args
, "reset", "-q", "--refresh", "--",
1805 add_pathspecs(&cp
.args
, ps
);
1806 if (run_command(&cp
)) {
1815 strbuf_release(&patch
);
1816 strbuf_release(&out
);
1817 free_stash_info(&info
);
1818 strbuf_release(&stash_msg_buf
);
1819 strbuf_release(&untracked_files
);
1823 static int push_stash(int argc
, const char **argv
, const char *prefix
,
1826 int force_assume
= 0;
1827 int keep_index
= -1;
1828 int only_staged
= 0;
1830 int include_untracked
= 0;
1832 int pathspec_file_nul
= 0;
1833 const char *stash_msg
= NULL
;
1834 char *pathspec_from_file
= NULL
;
1836 struct option options
[] = {
1837 OPT_BOOL('k', "keep-index", &keep_index
,
1839 OPT_BOOL('S', "staged", &only_staged
,
1840 N_("stash staged changes only")),
1841 OPT_BOOL('p', "patch", &patch_mode
,
1842 N_("stash in patch mode")),
1843 OPT__QUIET(&quiet
, N_("quiet mode")),
1844 OPT_BOOL('u', "include-untracked", &include_untracked
,
1845 N_("include untracked files in stash")),
1846 OPT_SET_INT('a', "all", &include_untracked
,
1847 N_("include ignore files"), 2),
1848 OPT_STRING('m', "message", &stash_msg
, N_("message"),
1849 N_("stash message")),
1850 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file
),
1851 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul
),
1857 int flags
= PARSE_OPT_KEEP_DASHDASH
;
1860 flags
|= PARSE_OPT_STOP_AT_NON_OPTION
;
1862 argc
= parse_options(argc
, argv
, prefix
, options
,
1863 push_assumed
? git_stash_usage
:
1864 git_stash_push_usage
, flags
);
1865 force_assume
|= patch_mode
;
1869 if (!strcmp(argv
[0], "--")) {
1872 } else if (push_assumed
&& !force_assume
) {
1873 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1878 parse_pathspec(&ps
, 0, PATHSPEC_PREFER_FULL
| PATHSPEC_PREFIX_ORIGIN
,
1881 if (pathspec_from_file
) {
1883 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1886 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1889 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1891 parse_pathspec_file(&ps
, 0,
1892 PATHSPEC_PREFER_FULL
| PATHSPEC_PREFIX_ORIGIN
,
1893 prefix
, pathspec_from_file
, pathspec_file_nul
);
1894 } else if (pathspec_file_nul
) {
1895 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1898 ret
= do_push_stash(&ps
, stash_msg
, quiet
, keep_index
, patch_mode
,
1899 include_untracked
, only_staged
);
1901 clear_pathspec(&ps
);
1902 free(pathspec_from_file
);
1906 static int push_stash_unassumed(int argc
, const char **argv
, const char *prefix
,
1907 struct repository
*repo UNUSED
)
1909 return push_stash(argc
, argv
, prefix
, 0);
1912 static int save_stash(int argc
, const char **argv
, const char *prefix
,
1913 struct repository
*repo UNUSED
)
1915 int keep_index
= -1;
1916 int only_staged
= 0;
1918 int include_untracked
= 0;
1921 const char *stash_msg
= NULL
;
1923 struct strbuf stash_msg_buf
= STRBUF_INIT
;
1924 struct option options
[] = {
1925 OPT_BOOL('k', "keep-index", &keep_index
,
1927 OPT_BOOL('S', "staged", &only_staged
,
1928 N_("stash staged changes only")),
1929 OPT_BOOL('p', "patch", &patch_mode
,
1930 N_("stash in patch mode")),
1931 OPT__QUIET(&quiet
, N_("quiet mode")),
1932 OPT_BOOL('u', "include-untracked", &include_untracked
,
1933 N_("include untracked files in stash")),
1934 OPT_SET_INT('a', "all", &include_untracked
,
1935 N_("include ignore files"), 2),
1936 OPT_STRING('m', "message", &stash_msg
, "message",
1937 N_("stash message")),
1941 argc
= parse_options(argc
, argv
, prefix
, options
,
1942 git_stash_save_usage
,
1943 PARSE_OPT_KEEP_DASHDASH
);
1946 stash_msg
= strbuf_join_argv(&stash_msg_buf
, argc
, argv
, ' ');
1948 memset(&ps
, 0, sizeof(ps
));
1949 ret
= do_push_stash(&ps
, stash_msg
, quiet
, keep_index
,
1950 patch_mode
, include_untracked
, only_staged
);
1952 strbuf_release(&stash_msg_buf
);
1956 static int write_commit_with_parents(struct repository
*r
,
1957 struct object_id
*out
,
1958 const struct object_id
*oid
,
1959 struct commit_list
*parents
)
1961 size_t author_len
, committer_len
;
1962 struct commit
*this;
1963 const char *orig_author
, *orig_committer
;
1964 char *author
= NULL
, *committer
= NULL
;
1966 unsigned long bufsize
;
1968 struct strbuf msg
= STRBUF_INIT
;
1970 struct ident_split id
;
1972 this = lookup_commit_reference(r
, oid
);
1973 buffer
= repo_get_commit_buffer(r
, this, &bufsize
);
1974 orig_author
= find_commit_header(buffer
, "author", &author_len
);
1975 orig_committer
= find_commit_header(buffer
, "committer", &committer_len
);
1977 if (!orig_author
|| !orig_committer
) {
1978 ret
= error(_("cannot parse commit %s"), oid_to_hex(oid
));
1982 if (split_ident_line(&id
, orig_author
, author_len
) < 0 ||
1983 split_ident_line(&id
, orig_committer
, committer_len
) < 0) {
1984 ret
= error(_("invalid author or committer for %s"), oid_to_hex(oid
));
1988 p
= strstr(buffer
, "\n\n");
1989 strbuf_addstr(&msg
, "git stash: ");
1992 strbuf_add(&msg
, p
+ 2, bufsize
- (p
+ 2 - buffer
));
1993 strbuf_complete_line(&msg
);
1995 author
= xmemdupz(orig_author
, author_len
);
1996 committer
= xmemdupz(orig_committer
, committer_len
);
1998 if (commit_tree_extended(msg
.buf
, msg
.len
,
1999 r
->hash_algo
->empty_tree
, parents
,
2000 out
, author
, committer
,
2002 ret
= error(_("could not write commit"));
2006 strbuf_release(&msg
);
2007 repo_unuse_commit_buffer(r
, this, buffer
);
2013 static int do_import_stash(struct repository
*r
, const char *rev
)
2015 struct object_id chain
;
2017 const char *buffer
= NULL
;
2018 unsigned long bufsize
;
2019 struct commit
*this = NULL
;
2020 struct commit_list
*items
= NULL
, *cur
;
2023 if (repo_get_oid(r
, rev
, &chain
))
2024 return error(_("not a valid revision: %s"), rev
);
2026 this = lookup_commit_reference(r
, &chain
);
2028 return error(_("not a commit: %s"), rev
);
2031 * Walk the commit history, finding each stash entry, and load data into
2035 const char *author
, *committer
;
2036 size_t author_len
, committer_len
;
2038 const char *expected
= "git stash <git@stash> 1000684800 +0000";
2039 const char *prefix
= "git stash: ";
2040 struct commit
*stash
;
2041 struct tree
*tree
= repo_get_commit_tree(r
, this);
2044 !oideq(&tree
->object
.oid
, r
->hash_algo
->empty_tree
) ||
2046 (!this->parents
->next
|| this->parents
->next
->next
))) {
2047 res
= error(_("%s is not a valid exported stash commit"),
2048 oid_to_hex(&this->object
.oid
));
2052 buffer
= repo_get_commit_buffer(r
, this, &bufsize
);
2054 if (!this->parents
) {
2056 * We don't have any parents. Make sure this is our
2059 author
= find_commit_header(buffer
, "author", &author_len
);
2060 committer
= find_commit_header(buffer
, "committer", &committer_len
);
2062 if (!author
|| !committer
) {
2063 error(_("cannot parse commit %s"), oid_to_hex(&this->object
.oid
));
2067 if (author_len
!= strlen(expected
) ||
2068 committer_len
!= strlen(expected
) ||
2069 memcmp(author
, expected
, author_len
) ||
2070 memcmp(committer
, expected
, committer_len
)) {
2071 res
= error(_("found root commit %s with invalid data"), oid_to_hex(&this->object
.oid
));
2077 p
= strstr(buffer
, "\n\n");
2079 res
= error(_("cannot parse commit %s"), oid_to_hex(&this->object
.oid
));
2084 if (((size_t)(bufsize
- (p
- buffer
)) < strlen(prefix
)) ||
2085 memcmp(prefix
, p
, strlen(prefix
))) {
2086 res
= error(_("found stash commit %s without expected prefix"), oid_to_hex(&this->object
.oid
));
2090 stash
= this->parents
->next
->item
;
2092 if (repo_parse_commit(r
, this->parents
->item
) ||
2093 repo_parse_commit(r
, stash
)) {
2094 res
= error(_("cannot parse parents of commit: %s"),
2095 oid_to_hex(&this->object
.oid
));
2099 if (check_stash_topology(r
, stash
)) {
2100 res
= error(_("%s does not look like a stash commit"),
2101 oid_to_hex(&stash
->object
.oid
));
2105 repo_unuse_commit_buffer(r
, this, buffer
);
2107 items
= commit_list_insert(stash
, &items
);
2108 this = this->parents
->item
;
2112 * Now, walk each entry, adding it to the stash as a normal stash
2115 for (cur
= items
; cur
; cur
= cur
->next
) {
2117 struct object_id
*oid
;
2120 oid
= &this->object
.oid
;
2121 buffer
= repo_get_commit_buffer(r
, this, &bufsize
);
2123 res
= error(_("cannot read commit buffer for %s"), oid_to_hex(oid
));
2127 p
= strstr(buffer
, "\n\n");
2129 res
= error(_("cannot parse commit %s"), oid_to_hex(oid
));
2134 msg
= xmemdupz(p
, bufsize
- (p
- buffer
));
2135 repo_unuse_commit_buffer(r
, this, buffer
);
2138 if (do_store_stash(oid
, msg
, 1)) {
2139 res
= error(_("cannot save the stash for %s"), oid_to_hex(oid
));
2146 repo_unuse_commit_buffer(r
, this, buffer
);
2147 free_commit_list(items
);
2153 static int import_stash(int argc
, const char **argv
, const char *prefix
,
2154 struct repository
*repo
)
2156 struct option options
[] = {
2160 argc
= parse_options(argc
, argv
, prefix
, options
,
2161 git_stash_import_usage
,
2162 PARSE_OPT_KEEP_DASHDASH
);
2165 usage_msg_opt("a revision is required", git_stash_import_usage
, options
);
2167 return do_import_stash(repo
, argv
[0]);
2170 struct stash_entry_data
{
2171 struct repository
*r
;
2172 struct commit_list
**items
;
2176 static int collect_stash_entries(struct object_id
*old_oid UNUSED
,
2177 struct object_id
*new_oid
,
2178 const char *committer UNUSED
,
2179 timestamp_t timestamp UNUSED
,
2180 int tz UNUSED
, const char *msg UNUSED
,
2183 struct stash_entry_data
*data
= cb_data
;
2184 struct commit
*stash
;
2187 stash
= lookup_commit_reference(data
->r
, new_oid
);
2188 if (!stash
|| check_stash_topology(data
->r
, stash
)) {
2189 return error(_("%s does not look like a stash commit"),
2190 oid_to_hex(new_oid
));
2192 data
->items
= commit_list_append(stash
, data
->items
);
2196 static int do_export_stash(struct repository
*r
,
2201 struct object_id base
;
2202 struct object_context unused
;
2203 struct commit
*prev
;
2204 struct commit_list
*items
= NULL
, **iter
= &items
, *cur
;
2207 struct strbuf revision
= STRBUF_INIT
;
2208 const char *author
, *committer
;
2211 * This is an arbitrary, fixed date, specifically the one used by git
2212 * format-patch. The goal is merely to produce reproducible output.
2214 prepare_fallback_ident("git stash", "git@stash");
2215 author
= fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT
,
2216 "2001-09-17T00:00:00Z", 0);
2217 committer
= fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT
,
2218 "2001-09-17T00:00:00Z", 0);
2220 /* First, we create a single empty commit. */
2221 if (commit_tree_extended("", 0, r
->hash_algo
->empty_tree
, NULL
,
2222 &base
, author
, committer
, NULL
, NULL
))
2223 return error(_("unable to write base commit"));
2225 prev
= lookup_commit_reference(r
, &base
);
2229 * Find each specified stash, and load data into the array.
2231 for (i
= 0; i
< argc
; i
++) {
2232 struct object_id oid
;
2233 struct commit
*stash
;
2235 if (parse_stash_revision(&revision
, argv
[i
], 1) ||
2236 get_oid_with_context(r
, revision
.buf
,
2237 GET_OID_QUIETLY
| GET_OID_GENTLY
,
2239 res
= error(_("unable to find stash entry %s"), argv
[i
]);
2243 stash
= lookup_commit_reference(r
, &oid
);
2244 if (!stash
|| check_stash_topology(r
, stash
)) {
2245 res
= error(_("%s does not look like a stash commit"),
2249 iter
= commit_list_append(stash
, iter
);
2253 * Walk the reflog, finding each stash entry, and load data into the
2256 struct stash_entry_data cb_data
= {
2257 .r
= r
, .items
= iter
,
2259 if (refs_for_each_reflog_ent_reverse(get_main_ref_store(r
),
2261 collect_stash_entries
,
2262 &cb_data
) && cb_data
.count
)
2267 * Now, create a set of commits identical to the regular stash commits,
2268 * but where their first parents form a chain to our original empty
2271 items
= reverse_commit_list(items
);
2272 for (cur
= items
; cur
; cur
= cur
->next
) {
2273 struct commit_list
*parents
= NULL
;
2274 struct commit_list
**next
= &parents
;
2275 struct object_id out
;
2276 struct commit
*stash
= cur
->item
;
2278 next
= commit_list_append(prev
, next
);
2279 next
= commit_list_append(stash
, next
);
2280 res
= write_commit_with_parents(r
, &out
, &stash
->object
.oid
, parents
);
2281 free_commit_list(parents
);
2284 prev
= lookup_commit_reference(r
, &out
);
2287 refs_update_ref(get_main_ref_store(r
), NULL
, ref
,
2288 &prev
->object
.oid
, NULL
, 0, UPDATE_REFS_DIE_ON_ERR
);
2290 puts(oid_to_hex(&prev
->object
.oid
));
2292 strbuf_release(&revision
);
2293 free_commit_list(items
);
2298 enum export_action
{
2304 static int export_stash(int argc
,
2307 struct repository
*repo
)
2309 const char *ref
= NULL
;
2310 enum export_action action
= ACTION_NONE
;
2311 struct option options
[] = {
2312 OPT_CMDMODE(0, "print", &action
,
2313 N_("print the object ID instead of writing it to a ref"),
2315 OPT_STRING(0, "to-ref", &ref
, "ref",
2316 N_("save the data to the given ref")),
2320 argc
= parse_options(argc
, argv
, prefix
, options
,
2321 git_stash_export_usage
,
2322 PARSE_OPT_KEEP_DASHDASH
);
2324 if (ref
&& action
== ACTION_NONE
)
2325 action
= ACTION_TO_REF
;
2327 if (action
== ACTION_NONE
|| (ref
&& action
== ACTION_PRINT
))
2328 return error(_("exactly one of --print and --to-ref is required"));
2330 return do_export_stash(repo
, ref
, argc
, argv
);
2333 int cmd_stash(int argc
,
2336 struct repository
*repo
)
2338 pid_t pid
= getpid();
2339 const char *index_file
;
2340 struct strvec args
= STRVEC_INIT
;
2341 parse_opt_subcommand_fn
*fn
= NULL
;
2342 struct option options
[] = {
2343 OPT_SUBCOMMAND("apply", &fn
, apply_stash
),
2344 OPT_SUBCOMMAND("clear", &fn
, clear_stash
),
2345 OPT_SUBCOMMAND("drop", &fn
, drop_stash
),
2346 OPT_SUBCOMMAND("pop", &fn
, pop_stash
),
2347 OPT_SUBCOMMAND("branch", &fn
, branch_stash
),
2348 OPT_SUBCOMMAND("list", &fn
, list_stash
),
2349 OPT_SUBCOMMAND("show", &fn
, show_stash
),
2350 OPT_SUBCOMMAND("store", &fn
, store_stash
),
2351 OPT_SUBCOMMAND("create", &fn
, create_stash
),
2352 OPT_SUBCOMMAND("push", &fn
, push_stash_unassumed
),
2353 OPT_SUBCOMMAND("export", &fn
, export_stash
),
2354 OPT_SUBCOMMAND("import", &fn
, import_stash
),
2355 OPT_SUBCOMMAND_F("save", &fn
, save_stash
, PARSE_OPT_NOCOMPLETE
),
2358 const char **args_copy
;
2361 git_config(git_stash_config
, NULL
);
2363 argc
= parse_options(argc
, argv
, prefix
, options
, git_stash_usage
,
2364 PARSE_OPT_SUBCOMMAND_OPTIONAL
|
2365 PARSE_OPT_KEEP_UNKNOWN_OPT
|
2366 PARSE_OPT_KEEP_DASHDASH
);
2368 prepare_repo_settings(the_repository
);
2369 the_repository
->settings
.command_requires_full_index
= 0;
2371 index_file
= repo_get_index_file(the_repository
);
2372 strbuf_addf(&stash_index_path
, "%s.stash.%" PRIuMAX
, index_file
,
2376 return !!fn(argc
, argv
, prefix
, repo
);
2378 return !!push_stash_unassumed(0, NULL
, prefix
, repo
);
2380 /* Assume 'stash push' */
2381 strvec_push(&args
, "push");
2382 strvec_pushv(&args
, argv
);
2385 * `push_stash()` ends up modifying the array, which causes memory
2386 * leaks if we didn't copy the array here.
2388 DUP_ARRAY(args_copy
, args
.v
, args
.nr
);
2390 ret
= !!push_stash(args
.nr
, args_copy
, prefix
, 1);
2392 strvec_clear(&args
);