]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/stash.c
e2f95cc2ebc219894ead5deea0807c0288cc4eec
[thirdparty/git.git] / builtin / stash.c
1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "builtin.h"
4 #include "abspath.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hash.h"
9 #include "hex.h"
10 #include "object-name.h"
11 #include "parse-options.h"
12 #include "refs.h"
13 #include "lockfile.h"
14 #include "cache-tree.h"
15 #include "unpack-trees.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 "repository.h"
24 #include "rerere.h"
25 #include "revision.h"
26 #include "setup.h"
27 #include "sparse-index.h"
28 #include "log-tree.h"
29 #include "diffcore.h"
30 #include "reflog.h"
31 #include "reflog-walk.h"
32 #include "add-interactive.h"
33 #include "oid-array.h"
34 #include "commit.h"
35
36 #define INCLUDE_ALL_FILES 2
37
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 \
67 "git stash clear"
68
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,
83 NULL
84 };
85
86 static const char * const git_stash_list_usage[] = {
87 BUILTIN_STASH_LIST_USAGE,
88 NULL
89 };
90
91 static const char * const git_stash_show_usage[] = {
92 BUILTIN_STASH_SHOW_USAGE,
93 NULL
94 };
95
96 static const char * const git_stash_drop_usage[] = {
97 BUILTIN_STASH_DROP_USAGE,
98 NULL
99 };
100
101 static const char * const git_stash_pop_usage[] = {
102 BUILTIN_STASH_POP_USAGE,
103 NULL
104 };
105
106 static const char * const git_stash_apply_usage[] = {
107 BUILTIN_STASH_APPLY_USAGE,
108 NULL
109 };
110
111 static const char * const git_stash_branch_usage[] = {
112 BUILTIN_STASH_BRANCH_USAGE,
113 NULL
114 };
115
116 static const char * const git_stash_clear_usage[] = {
117 BUILTIN_STASH_CLEAR_USAGE,
118 NULL
119 };
120
121 static const char * const git_stash_store_usage[] = {
122 BUILTIN_STASH_STORE_USAGE,
123 NULL
124 };
125
126 static const char * const git_stash_push_usage[] = {
127 BUILTIN_STASH_PUSH_USAGE,
128 NULL
129 };
130
131 static const char * const git_stash_save_usage[] = {
132 BUILTIN_STASH_SAVE_USAGE,
133 NULL
134 };
135
136 static const char * const git_stash_export_usage[] = {
137 BUILTIN_STASH_EXPORT_USAGE,
138 NULL
139 };
140
141 static const char * const git_stash_import_usage[] = {
142 BUILTIN_STASH_IMPORT_USAGE,
143 NULL
144 };
145
146 static const char ref_stash[] = "refs/stash";
147 static struct strbuf stash_index_path = STRBUF_INIT;
148
149 /*
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
159 */
160 struct stash_info {
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;
171 int is_stash_ref;
172 int has_u;
173 };
174
175 #define STASH_INFO_INIT { \
176 .revision = STRBUF_INIT, \
177 }
178
179 static void free_stash_info(struct stash_info *info)
180 {
181 strbuf_release(&info->revision);
182 }
183
184 static int check_stash_topology(struct repository *r, struct commit *stash)
185 {
186 struct commit *p1, *p2, *p3 = NULL;
187
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))
191 return -1;
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)))
198 return -1;
199 /* p2 must have a single parent, p3 must have no parents */
200 if (!p2->parents || p2->parents->next || (p3 && p3->parents))
201 return -1;
202 if (repo_parse_commit(r, p2->parents->item))
203 return -1;
204 /* p2^1 must equal p1 */
205 if (!oideq(&p1->object.oid, &p2->parents->item->object.oid))
206 return -1;
207
208 return 0;
209 }
210
211 static void assert_stash_like(struct stash_info *info, const char *revision)
212 {
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);
218 }
219
220 static int parse_stash_revision(struct strbuf *revision, const char *commit, int quiet)
221 {
222 strbuf_reset(revision);
223 if (!commit) {
224 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash)) {
225 if (!quiet)
226 fprintf_ln(stderr, _("No stash entries found."));
227 return -1;
228 }
229
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);
233 } else {
234 strbuf_addstr(revision, commit);
235 }
236 return 0;
237 }
238
239 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
240 {
241 int ret;
242 char *end_of_rev;
243 char *expanded_ref;
244 const char *revision;
245 const char *commit = NULL;
246 struct object_id dummy;
247 struct strbuf symbolic = STRBUF_INIT;
248
249 if (argc > 1) {
250 int i;
251 struct strbuf refs_msg = STRBUF_INIT;
252
253 for (i = 0; i < argc; i++)
254 strbuf_addf(&refs_msg, " '%s'", argv[i]);
255
256 fprintf_ln(stderr, _("Too many revisions specified:%s"),
257 refs_msg.buf);
258 strbuf_release(&refs_msg);
259
260 return -1;
261 }
262
263 if (argc == 1)
264 commit = argv[0];
265
266 strbuf_init(&info->revision, 0);
267 if (parse_stash_revision(&info->revision, commit, 0)) {
268 return -1;
269 }
270
271 revision = info->revision.buf;
272
273 if (repo_get_oid(the_repository, revision, &info->w_commit))
274 return error(_("%s is not a valid reference"), revision);
275
276 assert_stash_like(info, revision);
277
278 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
279
280 end_of_rev = strchrnul(revision, '@');
281 strbuf_add(&symbolic, revision, end_of_rev - revision);
282
283 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
284 &dummy, &expanded_ref, 0);
285 strbuf_release(&symbolic);
286 switch (ret) {
287 case 0: /* Not found, but valid ref */
288 info->is_stash_ref = 0;
289 break;
290 case 1:
291 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
292 break;
293 default: /* Invalid or ambiguous */
294 break;
295 }
296
297 free(expanded_ref);
298 return !(ret == 0 || ret == 1);
299 }
300
301 static int do_clear_stash(void)
302 {
303 struct object_id obj;
304 if (repo_get_oid(the_repository, ref_stash, &obj))
305 return 0;
306
307 return refs_delete_ref(get_main_ref_store(the_repository), NULL,
308 ref_stash, &obj, 0);
309 }
310
311 static int clear_stash(int argc, const char **argv, const char *prefix,
312 struct repository *repo UNUSED)
313 {
314 struct option options[] = {
315 OPT_END()
316 };
317
318 argc = parse_options(argc, argv, prefix, options,
319 git_stash_clear_usage,
320 PARSE_OPT_STOP_AT_NON_OPTION);
321
322 if (argc)
323 return error(_("git stash clear with arguments is "
324 "unimplemented"));
325
326 return do_clear_stash();
327 }
328
329 static int reset_tree(struct object_id *i_tree, int update, int reset)
330 {
331 int nr_trees = 1;
332 struct unpack_trees_options opts;
333 struct tree_desc t[MAX_UNPACK_TREES];
334 struct tree *tree;
335 struct lock_file lock_file = LOCK_INIT;
336
337 repo_read_index_preload(the_repository, NULL, 0);
338 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
339 return -1;
340
341 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
342
343 memset(&opts, 0, sizeof(opts));
344
345 tree = parse_tree_indirect(i_tree);
346 if (parse_tree(tree))
347 return -1;
348
349 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
350
351 opts.head_idx = 1;
352 opts.src_index = the_repository->index;
353 opts.dst_index = the_repository->index;
354 opts.merge = 1;
355 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
356 opts.update = update;
357 if (update)
358 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
359 opts.fn = oneway_merge;
360
361 if (unpack_trees(nr_trees, t, &opts))
362 return -1;
363
364 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
365 return error(_("unable to write new index file"));
366
367 return 0;
368 }
369
370 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
371 {
372 struct child_process cp = CHILD_PROCESS_INIT;
373 const char *w_commit_hex = oid_to_hex(w_commit);
374
375 /*
376 * Diff-tree would not be very hard to replace with a native function,
377 * however it should be done together with apply_cached.
378 */
379 cp.git_cmd = 1;
380 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
381 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
382
383 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
384 }
385
386 static int apply_cached(struct strbuf *out)
387 {
388 struct child_process cp = CHILD_PROCESS_INIT;
389
390 /*
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
393 * buffer.
394 */
395 cp.git_cmd = 1;
396 strvec_pushl(&cp.args, "apply", "--cached", NULL);
397 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
398 }
399
400 static int reset_head(void)
401 {
402 struct child_process cp = CHILD_PROCESS_INIT;
403
404 /*
405 * Reset is overall quite simple, however there is no current public
406 * API for resetting.
407 */
408 cp.git_cmd = 1;
409 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
410
411 return run_command(&cp);
412 }
413
414 static int is_path_a_directory(const char *path)
415 {
416 /*
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.
420 */
421 struct stat st;
422 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
423 }
424
425 static void add_diff_to_buf(struct diff_queue_struct *q,
426 struct diff_options *options UNUSED,
427 void *data)
428 {
429 int i;
430
431 for (i = 0; i < q->nr; i++) {
432 if (is_path_a_directory(q->queue[i]->one->path))
433 continue;
434
435 strbuf_addstr(data, q->queue[i]->one->path);
436
437 /* NUL-terminate: will be fed to update-index -z */
438 strbuf_addch(data, '\0');
439 }
440 }
441
442 static int restore_untracked(struct object_id *u_tree)
443 {
444 int res;
445 struct child_process cp = CHILD_PROCESS_INIT;
446
447 /*
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.
451 */
452 cp.git_cmd = 1;
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);
459 return -1;
460 }
461
462 child_process_init(&cp);
463 cp.git_cmd = 1;
464 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
465 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
466 stash_index_path.buf);
467
468 res = run_command(&cp);
469 remove_path(stash_index_path.buf);
470 return res;
471 }
472
473 static void unstage_changes_unless_new(struct object_id *orig_tree)
474 {
475 /*
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.
480 *
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.
484 */
485
486 struct checkout state = CHECKOUT_INIT;
487 struct diff_options diff_opts;
488 struct lock_file lock = LOCK_INIT;
489 int i;
490
491 /* If any entries have skip_worktree set, we'll have to check 'em out */
492 state.force = 1;
493 state.quiet = 1;
494 state.refresh_cache = 1;
495 state.istate = the_repository->index;
496
497 /*
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).
501 */
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);
507
508 do_diff_cache(orig_tree, &diff_opts);
509 diffcore_std(&diff_opts);
510
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;
515 int pos;
516
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));
521
522 /*
523 * Step 2: Place changes in the working tree
524 *
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.
529 */
530 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
531 struct stat st;
532
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;
537 int fd;
538
539 strbuf_addf(&new_path,
540 "%s.stash.XXXXXX", ce->name);
541 fd = xmkstemp(new_path.buf);
542 close(fd);
543 printf(_("WARNING: Untracked file in way of "
544 "tracked file! Renaming\n "
545 " %s -> %s\n"
546 " to make room.\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);
552 }
553 checkout_entry(ce, &state, NULL, NULL);
554 ce->ce_flags &= ~CE_SKIP_WORKTREE;
555 }
556
557 /*
558 * Step 3: "unstage" changes, as long as they are still tracked
559 */
560 if (p->one->oid_valid) {
561 /*
562 * Path existed in orig_tree; restore index entry
563 * from that tree in order to "unstage" the changes.
564 */
565 int option = ADD_CACHE_OK_TO_REPLACE;
566 if (pos < 0)
567 option = ADD_CACHE_OK_TO_ADD;
568
569 ce = make_cache_entry(the_repository->index,
570 p->one->mode,
571 &p->one->oid,
572 p->one->path,
573 0, 0);
574 add_index_entry(the_repository->index, ce, option);
575 }
576 }
577 diff_flush(&diff_opts);
578
579 /*
580 * Step 4: write the new index to disk
581 */
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"));
586 }
587
588 static int do_apply_stash(const char *prefix, struct stash_info *info,
589 int index, int quiet)
590 {
591 int clean, ret;
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;
598
599 repo_read_index_preload(the_repository, NULL, 0);
600 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
601 NULL, NULL, NULL))
602 return error(_("could not write index"));
603
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"));
607
608 if (index) {
609 if (oideq(&info->b_tree, &info->i_tree) ||
610 oideq(&c_tree, &info->i_tree)) {
611 has_index = 0;
612 } else {
613 struct strbuf out = STRBUF_INIT;
614
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));
619 }
620
621 ret = apply_cached(&out);
622 strbuf_release(&out);
623 if (ret)
624 return error(_("conflicts in index. "
625 "Try without --index."));
626
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"));
632
633 reset_head();
634 discard_index(the_repository->index);
635 repo_read_index(the_repository);
636 }
637 }
638
639 init_ui_merge_options(&o, the_repository);
640
641 o.branch1 = "Updated upstream";
642 o.branch2 = "Stashed changes";
643 o.ancestor = "Stash base";
644
645 if (oideq(&info->b_tree, &c_tree))
646 o.branch1 = "Version stash was based on";
647
648 if (quiet)
649 o.verbosity = 0;
650
651 if (o.verbosity >= 3)
652 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
653
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);
657
658 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
659 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
660
661 /*
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
664 * an error.
665 */
666 ret = clean >= 0 ? !clean : clean;
667
668 if (ret < 0)
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"));
673
674 if (ret) {
675 repo_rerere(the_repository, 0);
676
677 if (index)
678 fprintf_ln(stderr, _("Index was not unstashed."));
679
680 goto restore_untracked;
681 }
682
683 if (has_index) {
684 if (reset_tree(&index_tree, 0, 0))
685 ret = -1;
686 } else {
687 unstage_changes_unless_new(&c_tree);
688 }
689
690 restore_untracked:
691 if (info->has_u && restore_untracked(&info->u_tree))
692 ret = error(_("could not restore untracked files from stash"));
693
694 if (!quiet) {
695 struct child_process cp = CHILD_PROCESS_INIT;
696
697 /*
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.
701 */
702 cp.git_cmd = 1;
703 cp.dir = prefix;
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");
709 run_command(&cp);
710 }
711
712 return ret;
713 }
714
715 static int apply_stash(int argc, const char **argv, const char *prefix,
716 struct repository *repo UNUSED)
717 {
718 int ret = -1;
719 int quiet = 0;
720 int index = 0;
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")),
726 OPT_END()
727 };
728
729 argc = parse_options(argc, argv, prefix, options,
730 git_stash_apply_usage, 0);
731
732 if (get_stash_info(&info, argc, argv))
733 goto cleanup;
734
735 ret = do_apply_stash(prefix, &info, index, quiet);
736 cleanup:
737 free_stash_info(&info);
738 return ret;
739 }
740
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)
747 {
748 return 1;
749 }
750
751 static int reflog_is_empty(const char *refname)
752 {
753 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository),
754 refname, reject_reflog_ent, NULL);
755 }
756
757 static int do_drop_stash(struct stash_info *info, int quiet)
758 {
759 if (!reflog_delete(info->revision.buf,
760 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
761 0)) {
762 if (!quiet)
763 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
764 oid_to_hex(&info->w_commit));
765 } else {
766 return error(_("%s: Could not drop stash entry"),
767 info->revision.buf);
768 }
769
770 if (reflog_is_empty(ref_stash))
771 do_clear_stash();
772
773 return 0;
774 }
775
776 static int get_stash_info_assert(struct stash_info *info, int argc,
777 const char **argv)
778 {
779 int ret = get_stash_info(info, argc, argv);
780
781 if (ret < 0)
782 return ret;
783
784 if (!info->is_stash_ref)
785 return error(_("'%s' is not a stash reference"), info->revision.buf);
786
787 return 0;
788 }
789
790 static int drop_stash(int argc, const char **argv, const char *prefix,
791 struct repository *repo UNUSED)
792 {
793 int ret = -1;
794 int quiet = 0;
795 struct stash_info info = STASH_INFO_INIT;
796 struct option options[] = {
797 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
798 OPT_END()
799 };
800
801 argc = parse_options(argc, argv, prefix, options,
802 git_stash_drop_usage, 0);
803
804 if (get_stash_info_assert(&info, argc, argv))
805 goto cleanup;
806
807 ret = do_drop_stash(&info, quiet);
808 cleanup:
809 free_stash_info(&info);
810 return ret;
811 }
812
813 static int pop_stash(int argc, const char **argv, const char *prefix,
814 struct repository *repo UNUSED)
815 {
816 int ret = -1;
817 int index = 0;
818 int quiet = 0;
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")),
824 OPT_END()
825 };
826
827 argc = parse_options(argc, argv, prefix, options,
828 git_stash_pop_usage, 0);
829
830 if (get_stash_info_assert(&info, argc, argv))
831 goto cleanup;
832
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."));
836 else
837 ret = do_drop_stash(&info, quiet);
838
839 cleanup:
840 free_stash_info(&info);
841 return ret;
842 }
843
844 static int branch_stash(int argc, const char **argv, const char *prefix,
845 struct repository *repo UNUSED)
846 {
847 int ret = -1;
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[] = {
852 OPT_END()
853 };
854
855 argc = parse_options(argc, argv, prefix, options,
856 git_stash_branch_usage, 0);
857
858 if (!argc) {
859 fprintf_ln(stderr, _("No branch name specified"));
860 return -1;
861 }
862
863 branch = argv[0];
864
865 if (get_stash_info(&info, argc - 1, argv + 1))
866 goto cleanup;
867
868 cp.git_cmd = 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);
873 if (!ret)
874 ret = do_apply_stash(prefix, &info, 1, 0);
875 if (!ret && info.is_stash_ref)
876 ret = do_drop_stash(&info, 0);
877
878 cleanup:
879 free_stash_info(&info);
880 return ret;
881 }
882
883 static int list_stash(int argc, const char **argv, const char *prefix,
884 struct repository *repo UNUSED)
885 {
886 struct child_process cp = CHILD_PROCESS_INIT;
887 struct option options[] = {
888 OPT_END()
889 };
890
891 argc = parse_options(argc, argv, prefix, options,
892 git_stash_list_usage,
893 PARSE_OPT_KEEP_UNKNOWN_OPT);
894
895 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash))
896 return 0;
897
898 cp.git_cmd = 1;
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);
905 }
906
907 static int show_stat = 1;
908 static int show_patch;
909 static int show_include_untracked;
910
911 static int git_stash_config(const char *var, const char *value,
912 const struct config_context *ctx, void *cb)
913 {
914 if (!strcmp(var, "stash.showstat")) {
915 show_stat = git_config_bool(var, value);
916 return 0;
917 }
918 if (!strcmp(var, "stash.showpatch")) {
919 show_patch = git_config_bool(var, value);
920 return 0;
921 }
922 if (!strcmp(var, "stash.showincludeuntracked")) {
923 show_include_untracked = git_config_bool(var, value);
924 return 0;
925 }
926 return git_diff_basic_config(var, value, ctx, cb);
927 }
928
929 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
930 {
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 };
935
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);
942 }
943
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;
949
950 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
951 die(_("failed to unpack trees"));
952
953 do_diff_cache(&info->b_commit, diff_opt);
954 }
955
956 static int show_stash(int argc, const char **argv, const char *prefix,
957 struct repository *repo UNUSED)
958 {
959 int i;
960 int ret = -1;
961 struct stash_info info = STASH_INFO_INIT;
962 struct rev_info rev;
963 struct strvec stash_args = STRVEC_INIT;
964 struct strvec revision_args = STRVEC_INIT;
965 enum {
966 UNTRACKED_NONE,
967 UNTRACKED_INCLUDE,
968 UNTRACKED_ONLY
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"),
973 UNTRACKED_INCLUDE),
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),
977 OPT_END()
978 };
979 int do_usage = 0;
980
981 init_diff_ui_defaults();
982 git_config(git_diff_ui_config, NULL);
983 repo_init_revisions(the_repository, &rev, prefix);
984
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);
988
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]);
993 else
994 strvec_push(&revision_args, argv[i]);
995 }
996
997 if (get_stash_info(&info, stash_args.nr, stash_args.v))
998 goto cleanup;
999
1000 /*
1001 * The config settings are applied only if there are not passed
1002 * any options.
1003 */
1004 if (revision_args.nr == 1) {
1005 if (show_stat)
1006 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
1007
1008 if (show_patch)
1009 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1010
1011 if (!show_stat && !show_patch) {
1012 ret = 0;
1013 goto cleanup;
1014 }
1015 }
1016
1017 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
1018 if (argc > 1)
1019 goto usage;
1020 if (!rev.diffopt.output_format) {
1021 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
1022 diff_setup_done(&rev.diffopt);
1023 }
1024
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);
1030 break;
1031 case UNTRACKED_ONLY:
1032 if (info.has_u)
1033 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
1034 break;
1035 case UNTRACKED_INCLUDE:
1036 if (info.has_u)
1037 diff_include_untracked(&info, &rev.diffopt);
1038 else
1039 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
1040 break;
1041 }
1042 log_tree_diff_flush(&rev);
1043
1044 ret = diff_result_code(&rev);
1045
1046 cleanup:
1047 strvec_clear(&revision_args);
1048 strvec_clear(&stash_args);
1049 free_stash_info(&info);
1050 release_revisions(&rev);
1051 if (do_usage)
1052 usage_with_options(git_stash_show_usage, options);
1053 return ret;
1054 usage:
1055 do_usage = 1;
1056 goto cleanup;
1057 }
1058
1059 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
1060 int quiet)
1061 {
1062 struct stash_info info;
1063 char revision[GIT_MAX_HEXSZ];
1064
1065 oid_to_hex_r(revision, w_commit);
1066 assert_stash_like(&info, revision);
1067
1068 if (!stash_msg)
1069 stash_msg = "Created via \"git stash store\".";
1070
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)) {
1075 if (!quiet) {
1076 fprintf_ln(stderr, _("Cannot update %s with %s"),
1077 ref_stash, oid_to_hex(w_commit));
1078 }
1079 return -1;
1080 }
1081
1082 return 0;
1083 }
1084
1085 static int store_stash(int argc, const char **argv, const char *prefix,
1086 struct repository *repo UNUSED)
1087 {
1088 int quiet = 0;
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")),
1096 OPT_END()
1097 };
1098 int ret;
1099
1100 argc = parse_options(argc, argv, prefix, options,
1101 git_stash_store_usage,
1102 PARSE_OPT_KEEP_UNKNOWN_OPT);
1103
1104 if (argc != 1) {
1105 if (!quiet)
1106 fprintf_ln(stderr, _("\"git stash store\" requires one "
1107 "<commit> argument"));
1108 return -1;
1109 }
1110
1111 if (get_oid_with_context(the_repository,
1112 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1113 &dummy)) {
1114 if (!quiet)
1115 fprintf_ln(stderr, _("Cannot update %s with %s"),
1116 ref_stash, argv[0]);
1117 ret = -1;
1118 goto out;
1119 }
1120
1121 ret = do_store_stash(&obj, stash_msg, quiet);
1122
1123 out:
1124 object_context_release(&dummy);
1125 return ret;
1126 }
1127
1128 static void add_pathspecs(struct strvec *args,
1129 const struct pathspec *ps) {
1130 int i;
1131
1132 for (i = 0; i < ps->nr; i++)
1133 strvec_push(args, ps->items[i].original);
1134 }
1135
1136 /*
1137 * `untracked_files` will be filled with the names of untracked files.
1138 * The return value is:
1139 *
1140 * = 0 if there are not any untracked files
1141 * > 0 if there are untracked files
1142 */
1143 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1144 struct strbuf *untracked_files)
1145 {
1146 int i;
1147 int found = 0;
1148 struct dir_struct dir = DIR_INIT;
1149
1150 if (include_untracked != INCLUDE_ALL_FILES)
1151 setup_standard_excludes(&dir);
1152
1153 fill_directory(&dir, the_repository->index, ps);
1154 for (i = 0; i < dir.nr; i++) {
1155 struct dir_entry *ent = dir.entries[i];
1156 found++;
1157 strbuf_addstr(untracked_files, ent->name);
1158 /* NUL-terminate: will be fed to update-index -z */
1159 strbuf_addch(untracked_files, '\0');
1160 }
1161
1162 dir_clear(&dir);
1163 return found;
1164 }
1165
1166 /*
1167 * The return value of `check_changes_tracked_files()` can be:
1168 *
1169 * < 0 if there was an error
1170 * = 0 if there are no changes.
1171 * > 0 if there are changes.
1172 */
1173 static int check_changes_tracked_files(const struct pathspec *ps)
1174 {
1175 struct rev_info rev;
1176 struct object_id dummy;
1177 int ret = 0;
1178
1179 /* No initial commit. */
1180 if (repo_get_oid(the_repository, "HEAD", &dummy))
1181 return -1;
1182
1183 if (repo_read_index(the_repository) < 0)
1184 return -1;
1185
1186 repo_init_revisions(the_repository, &rev, NULL);
1187 copy_pathspec(&rev.prune_data, ps);
1188
1189 rev.diffopt.flags.quick = 1;
1190 rev.diffopt.flags.ignore_submodules = 1;
1191 rev.abbrev = 0;
1192
1193 add_head_to_pending(&rev);
1194 diff_setup_done(&rev.diffopt);
1195
1196 run_diff_index(&rev, DIFF_INDEX_CACHED);
1197 if (diff_result_code(&rev)) {
1198 ret = 1;
1199 goto done;
1200 }
1201
1202 run_diff_files(&rev, 0);
1203 if (diff_result_code(&rev)) {
1204 ret = 1;
1205 goto done;
1206 }
1207
1208 done:
1209 release_revisions(&rev);
1210 return ret;
1211 }
1212
1213 /*
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.
1216 */
1217 static int check_changes(const struct pathspec *ps, int include_untracked,
1218 struct strbuf *untracked_files)
1219 {
1220 int ret = 0;
1221 if (check_changes_tracked_files(ps))
1222 ret = 1;
1223
1224 if (include_untracked && get_untracked_files(ps, include_untracked,
1225 untracked_files))
1226 ret = 1;
1227
1228 return ret;
1229 }
1230
1231 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1232 struct strbuf files)
1233 {
1234 int ret = 0;
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);
1238
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);
1244
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,
1247 NULL, 0)) {
1248 ret = -1;
1249 goto done;
1250 }
1251
1252 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1253 NULL)) {
1254 ret = -1;
1255 goto done;
1256 }
1257
1258 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1259 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1260 ret = -1;
1261 goto done;
1262 }
1263
1264 done:
1265 release_index(&istate);
1266 strbuf_release(&untracked_msg);
1267 remove_path(stash_index_path.buf);
1268 return ret;
1269 }
1270
1271 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1272 int quiet)
1273 {
1274 int ret = 0;
1275 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1276 struct index_state istate = INDEX_STATE_INIT(the_repository);
1277
1278 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1279 0, NULL)) {
1280 ret = -1;
1281 goto done;
1282 }
1283
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)) {
1288 ret = -1;
1289 goto done;
1290 }
1291
1292 if (!out_patch->len) {
1293 if (!quiet)
1294 fprintf_ln(stderr, _("No staged changes"));
1295 ret = 1;
1296 }
1297
1298 done:
1299 release_index(&istate);
1300 return ret;
1301 }
1302
1303 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1304 struct strbuf *out_patch, int quiet)
1305 {
1306 int ret = 0;
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;
1311
1312 remove_path(stash_index_path.buf);
1313
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)) {
1319 ret = -1;
1320 goto done;
1321 }
1322
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);
1328
1329 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1330
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);
1334 else
1335 unsetenv(INDEX_ENVIRONMENT);
1336 FREE_AND_NULL(old_index_env);
1337
1338 /* State of the working tree. */
1339 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1340 NULL)) {
1341 ret = -1;
1342 goto done;
1343 }
1344
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)) {
1349 ret = -1;
1350 goto done;
1351 }
1352
1353 if (!out_patch->len) {
1354 if (!quiet)
1355 fprintf_ln(stderr, _("No changes selected"));
1356 ret = 1;
1357 }
1358
1359 done:
1360 release_index(&istate);
1361 remove_path(stash_index_path.buf);
1362 return ret;
1363 }
1364
1365 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1366 {
1367 int ret = 0;
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);
1372
1373 repo_init_revisions(the_repository, &rev, NULL);
1374 copy_pathspec(&rev.prune_data, ps);
1375
1376 set_alternate_index_output(stash_index_path.buf);
1377 if (reset_tree(&info->i_tree, 0, 0)) {
1378 ret = -1;
1379 goto done;
1380 }
1381 set_alternate_index_output(NULL);
1382
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;
1386
1387 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1388 ret = -1;
1389 goto done;
1390 }
1391
1392 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1393 "");
1394 run_diff_index(&rev, 0);
1395
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);
1402
1403 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1404 NULL, 0, NULL, 0)) {
1405 ret = -1;
1406 goto done;
1407 }
1408
1409 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1410 NULL)) {
1411 ret = -1;
1412 goto done;
1413 }
1414
1415 done:
1416 release_index(&istate);
1417 release_revisions(&rev);
1418 strbuf_release(&diff_output);
1419 remove_path(stash_index_path.buf);
1420 return ret;
1421 }
1422
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,
1426 int quiet)
1427 {
1428 int ret = 0;
1429 int flags = 0;
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;
1440
1441 prepare_fallback_ident("git stash", "git@stash");
1442
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"));
1447 goto done;
1448 }
1449
1450 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1451 if (!quiet)
1452 fprintf_ln(stderr, _("You do not have "
1453 "the initial commit yet"));
1454 ret = -1;
1455 goto done;
1456 } else {
1457 head_commit = lookup_commit(the_repository, &info->b_commit);
1458 }
1459
1460 if (!check_changes(ps, include_untracked, &untracked_files)) {
1461 ret = 1;
1462 goto done;
1463 }
1464
1465 branch_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1466 "HEAD", 0, NULL, &flags);
1467
1468 if (flags & REF_ISSYMREF) {
1469 if (skip_prefix(branch_ref, "refs/heads/", &branch_name))
1470 branch_name = branch_name_buf = xstrdup(branch_name);
1471 }
1472
1473 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1474 &head_commit->object.oid,
1475 DEFAULT_ABBREV);
1476 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1477 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1478
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)) {
1485 if (!quiet)
1486 fprintf_ln(stderr, _("Cannot save the current "
1487 "index state"));
1488 ret = -1;
1489 goto done;
1490 }
1491
1492 free_commit_list(parents);
1493 parents = NULL;
1494
1495 if (include_untracked) {
1496 if (save_untracked_files(info, &msg, untracked_files)) {
1497 if (!quiet)
1498 fprintf_ln(stderr, _("Cannot save "
1499 "the untracked files"));
1500 ret = -1;
1501 goto done;
1502 }
1503 untracked_commit_option = 1;
1504 }
1505 if (patch_mode) {
1506 ret = stash_patch(info, ps, patch, quiet);
1507 if (ret < 0) {
1508 if (!quiet)
1509 fprintf_ln(stderr, _("Cannot save the current "
1510 "worktree state"));
1511 goto done;
1512 } else if (ret > 0) {
1513 goto done;
1514 }
1515 } else if (only_staged) {
1516 ret = stash_staged(info, patch, quiet);
1517 if (ret < 0) {
1518 if (!quiet)
1519 fprintf_ln(stderr, _("Cannot save the current "
1520 "staged state"));
1521 goto done;
1522 } else if (ret > 0) {
1523 goto done;
1524 }
1525 } else {
1526 if (stash_working_tree(info, ps)) {
1527 if (!quiet)
1528 fprintf_ln(stderr, _("Cannot save the current "
1529 "worktree state"));
1530 ret = -1;
1531 goto done;
1532 }
1533 }
1534
1535 if (!stash_msg_buf->len)
1536 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1537 else
1538 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1539
1540 if (untracked_commit_option)
1541 commit_list_insert(lookup_commit(the_repository,
1542 &info->u_commit),
1543 &parents);
1544 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1545 &parents);
1546 commit_list_insert(head_commit, &parents);
1547
1548 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1549 parents, &info->w_commit, NULL, NULL)) {
1550 if (!quiet)
1551 fprintf_ln(stderr, _("Cannot record "
1552 "working tree state"));
1553 ret = -1;
1554 goto done;
1555 }
1556
1557 done:
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);
1563 return ret;
1564 }
1565
1566 static int create_stash(int argc, const char **argv, const char *prefix UNUSED,
1567 struct repository *repo UNUSED)
1568 {
1569 int ret;
1570 struct strbuf stash_msg_buf = STRBUF_INIT;
1571 struct stash_info info = STASH_INFO_INIT;
1572 struct pathspec ps;
1573
1574 /* Starting with argv[1], since argv[0] is "create" */
1575 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1576
1577 memset(&ps, 0, sizeof(ps));
1578 if (!check_changes_tracked_files(&ps))
1579 return 0;
1580
1581 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1582 NULL, 0);
1583 if (!ret)
1584 printf_ln("%s", oid_to_hex(&info.w_commit));
1585
1586 free_stash_info(&info);
1587 strbuf_release(&stash_msg_buf);
1588 return ret;
1589 }
1590
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)
1593 {
1594 int ret = 0;
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;
1600
1601 if (patch_mode && keep_index == -1)
1602 keep_index = 1;
1603
1604 if (patch_mode && include_untracked) {
1605 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1606 " or --all at the same time"));
1607 ret = -1;
1608 goto done;
1609 }
1610
1611 /* --patch overrides --staged */
1612 if (patch_mode)
1613 only_staged = 0;
1614
1615 if (only_staged && include_untracked) {
1616 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1617 " or --all at the same time"));
1618 ret = -1;
1619 goto done;
1620 }
1621
1622 repo_read_index_preload(the_repository, NULL, 0);
1623 if (!include_untracked && ps->nr) {
1624 char *ps_matched = xcalloc(ps->nr, 1);
1625
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,
1630 ps_matched);
1631
1632 if (report_path_error(ps_matched, ps)) {
1633 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1634 ret = -1;
1635 free(ps_matched);
1636 goto done;
1637 }
1638 free(ps_matched);
1639 }
1640
1641 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1642 NULL, NULL, NULL)) {
1643 ret = error(_("could not write index"));
1644 goto done;
1645 }
1646
1647 if (!check_changes(ps, include_untracked, &untracked_files)) {
1648 if (!quiet)
1649 printf_ln(_("No local changes to save"));
1650 goto done;
1651 }
1652
1653 if (!refs_reflog_exists(get_main_ref_store(the_repository), ref_stash) && do_clear_stash()) {
1654 ret = -1;
1655 if (!quiet)
1656 fprintf_ln(stderr, _("Cannot initialize stash"));
1657 goto done;
1658 }
1659
1660 if (stash_msg)
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)) {
1664 ret = -1;
1665 goto done;
1666 }
1667
1668 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1669 ret = -1;
1670 if (!quiet)
1671 fprintf_ln(stderr, _("Cannot save the current status"));
1672 goto done;
1673 }
1674
1675 if (!quiet)
1676 printf_ln(_("Saved working directory and index state %s"),
1677 stash_msg_buf.buf);
1678
1679 if (!(patch_mode || only_staged)) {
1680 if (include_untracked && !ps->nr) {
1681 struct child_process cp = CHILD_PROCESS_INIT;
1682
1683 cp.git_cmd = 1;
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);
1689 }
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)) {
1695 ret = -1;
1696 goto done;
1697 }
1698 }
1699 discard_index(the_repository->index);
1700 if (ps->nr) {
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;
1704
1705 cp_add.git_cmd = 1;
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)) {
1714 ret = -1;
1715 goto done;
1716 }
1717
1718 cp_diff.git_cmd = 1;
1719 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1720 "--cached", "--binary", "HEAD", "--",
1721 NULL);
1722 add_pathspecs(&cp_diff.args, ps);
1723 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1724 ret = -1;
1725 goto done;
1726 }
1727
1728 cp_apply.git_cmd = 1;
1729 strvec_pushl(&cp_apply.args, "apply", "--index",
1730 "-R", NULL);
1731 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1732 NULL, 0)) {
1733 ret = -1;
1734 goto done;
1735 }
1736 } else {
1737 struct child_process cp = CHILD_PROCESS_INIT;
1738 cp.git_cmd = 1;
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)) {
1743 ret = -1;
1744 goto done;
1745 }
1746 }
1747
1748 /*
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:
1753 *
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.
1757 *
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.
1763 *
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.
1767 */
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;
1771
1772 cp.git_cmd = 1;
1773 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1774 oid_to_hex(&info.i_tree), "--", NULL);
1775 if (!ps->nr)
1776 strvec_push(&cp.args, ":/");
1777 else
1778 add_pathspecs(&cp.args, ps);
1779 if (run_command(&cp)) {
1780 ret = -1;
1781 goto done;
1782 }
1783 }
1784 goto done;
1785 } else {
1786 struct child_process cp = CHILD_PROCESS_INIT;
1787
1788 cp.git_cmd = 1;
1789 strvec_pushl(&cp.args, "apply", "-R", NULL);
1790
1791 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1792 if (!quiet)
1793 fprintf_ln(stderr, _("Cannot remove "
1794 "worktree changes"));
1795 ret = -1;
1796 goto done;
1797 }
1798
1799 if (keep_index < 1) {
1800 struct child_process cp = CHILD_PROCESS_INIT;
1801
1802 cp.git_cmd = 1;
1803 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1804 NULL);
1805 add_pathspecs(&cp.args, ps);
1806 if (run_command(&cp)) {
1807 ret = -1;
1808 goto done;
1809 }
1810 }
1811 goto done;
1812 }
1813
1814 done:
1815 strbuf_release(&patch);
1816 strbuf_release(&out);
1817 free_stash_info(&info);
1818 strbuf_release(&stash_msg_buf);
1819 strbuf_release(&untracked_files);
1820 return ret;
1821 }
1822
1823 static int push_stash(int argc, const char **argv, const char *prefix,
1824 int push_assumed)
1825 {
1826 int force_assume = 0;
1827 int keep_index = -1;
1828 int only_staged = 0;
1829 int patch_mode = 0;
1830 int include_untracked = 0;
1831 int quiet = 0;
1832 int pathspec_file_nul = 0;
1833 const char *stash_msg = NULL;
1834 char *pathspec_from_file = NULL;
1835 struct pathspec ps;
1836 struct option options[] = {
1837 OPT_BOOL('k', "keep-index", &keep_index,
1838 N_("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),
1852 OPT_END()
1853 };
1854 int ret;
1855
1856 if (argc) {
1857 int flags = PARSE_OPT_KEEP_DASHDASH;
1858
1859 if (push_assumed)
1860 flags |= PARSE_OPT_STOP_AT_NON_OPTION;
1861
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;
1866 }
1867
1868 if (argc) {
1869 if (!strcmp(argv[0], "--")) {
1870 argc--;
1871 argv++;
1872 } else if (push_assumed && !force_assume) {
1873 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1874 argv[0]);
1875 }
1876 }
1877
1878 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1879 prefix, argv);
1880
1881 if (pathspec_from_file) {
1882 if (patch_mode)
1883 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1884
1885 if (only_staged)
1886 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1887
1888 if (ps.nr)
1889 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1890
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");
1896 }
1897
1898 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1899 include_untracked, only_staged);
1900
1901 clear_pathspec(&ps);
1902 free(pathspec_from_file);
1903 return ret;
1904 }
1905
1906 static int push_stash_unassumed(int argc, const char **argv, const char *prefix,
1907 struct repository *repo UNUSED)
1908 {
1909 return push_stash(argc, argv, prefix, 0);
1910 }
1911
1912 static int save_stash(int argc, const char **argv, const char *prefix,
1913 struct repository *repo UNUSED)
1914 {
1915 int keep_index = -1;
1916 int only_staged = 0;
1917 int patch_mode = 0;
1918 int include_untracked = 0;
1919 int quiet = 0;
1920 int ret = 0;
1921 const char *stash_msg = NULL;
1922 struct pathspec ps;
1923 struct strbuf stash_msg_buf = STRBUF_INIT;
1924 struct option options[] = {
1925 OPT_BOOL('k', "keep-index", &keep_index,
1926 N_("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")),
1938 OPT_END()
1939 };
1940
1941 argc = parse_options(argc, argv, prefix, options,
1942 git_stash_save_usage,
1943 PARSE_OPT_KEEP_DASHDASH);
1944
1945 if (argc)
1946 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1947
1948 memset(&ps, 0, sizeof(ps));
1949 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1950 patch_mode, include_untracked, only_staged);
1951
1952 strbuf_release(&stash_msg_buf);
1953 return ret;
1954 }
1955
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)
1960 {
1961 size_t author_len, committer_len;
1962 struct commit *this;
1963 const char *orig_author, *orig_committer;
1964 char *author = NULL, *committer = NULL;
1965 const char *buffer;
1966 unsigned long bufsize;
1967 const char *p;
1968 struct strbuf msg = STRBUF_INIT;
1969 int ret = 0;
1970 struct ident_split id;
1971
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);
1976
1977 if (!orig_author || !orig_committer) {
1978 ret = error(_("cannot parse commit %s"), oid_to_hex(oid));
1979 goto out;
1980 }
1981
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));
1985 goto out;
1986 }
1987
1988 p = strstr(buffer, "\n\n");
1989 strbuf_addstr(&msg, "git stash: ");
1990
1991 if (p)
1992 strbuf_add(&msg, p + 2, bufsize - (p + 2 - buffer));
1993 strbuf_complete_line(&msg);
1994
1995 author = xmemdupz(orig_author, author_len);
1996 committer = xmemdupz(orig_committer, committer_len);
1997
1998 if (commit_tree_extended(msg.buf, msg.len,
1999 r->hash_algo->empty_tree, parents,
2000 out, author, committer,
2001 NULL, NULL)) {
2002 ret = error(_("could not write commit"));
2003 goto out;
2004 }
2005 out:
2006 strbuf_release(&msg);
2007 repo_unuse_commit_buffer(r, this, buffer);
2008 free(author);
2009 free(committer);
2010 return ret;
2011 }
2012
2013 static int do_import_stash(struct repository *r, const char *rev)
2014 {
2015 struct object_id chain;
2016 int res = 0;
2017 const char *buffer = NULL;
2018 unsigned long bufsize;
2019 struct commit *this = NULL;
2020 struct commit_list *items = NULL, *cur;
2021 char *msg = NULL;
2022
2023 if (repo_get_oid(r, rev, &chain))
2024 return error(_("not a valid revision: %s"), rev);
2025
2026 this = lookup_commit_reference(r, &chain);
2027 if (!this)
2028 return error(_("not a commit: %s"), rev);
2029
2030 /*
2031 * Walk the commit history, finding each stash entry, and load data into
2032 * the array.
2033 */
2034 for (;;) {
2035 const char *author, *committer;
2036 size_t author_len, committer_len;
2037 const char *p;
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);
2042
2043 if (!tree ||
2044 !oideq(&tree->object.oid, r->hash_algo->empty_tree) ||
2045 (this->parents &&
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));
2049 goto out;
2050 }
2051
2052 buffer = repo_get_commit_buffer(r, this, &bufsize);
2053
2054 if (!this->parents) {
2055 /*
2056 * We don't have any parents. Make sure this is our
2057 * root commit.
2058 */
2059 author = find_commit_header(buffer, "author", &author_len);
2060 committer = find_commit_header(buffer, "committer", &committer_len);
2061
2062 if (!author || !committer) {
2063 error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2064 goto out;
2065 }
2066
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));
2072 goto out;
2073 }
2074 break;
2075 }
2076
2077 p = strstr(buffer, "\n\n");
2078 if (!p) {
2079 res = error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2080 goto out;
2081 }
2082
2083 p += 2;
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));
2087 goto out;
2088 }
2089
2090 stash = this->parents->next->item;
2091
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));
2096 goto out;
2097 }
2098
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));
2102 goto out;
2103 }
2104
2105 repo_unuse_commit_buffer(r, this, buffer);
2106 buffer = NULL;
2107 items = commit_list_insert(stash, &items);
2108 this = this->parents->item;
2109 }
2110
2111 /*
2112 * Now, walk each entry, adding it to the stash as a normal stash
2113 * commit.
2114 */
2115 for (cur = items; cur; cur = cur->next) {
2116 const char *p;
2117 struct object_id *oid;
2118
2119 this = cur->item;
2120 oid = &this->object.oid;
2121 buffer = repo_get_commit_buffer(r, this, &bufsize);
2122 if (!buffer) {
2123 res = error(_("cannot read commit buffer for %s"), oid_to_hex(oid));
2124 goto out;
2125 }
2126
2127 p = strstr(buffer, "\n\n");
2128 if (!p) {
2129 res = error(_("cannot parse commit %s"), oid_to_hex(oid));
2130 goto out;
2131 }
2132
2133 p += 2;
2134 msg = xmemdupz(p, bufsize - (p - buffer));
2135 repo_unuse_commit_buffer(r, this, buffer);
2136 buffer = NULL;
2137
2138 if (do_store_stash(oid, msg, 1)) {
2139 res = error(_("cannot save the stash for %s"), oid_to_hex(oid));
2140 goto out;
2141 }
2142 FREE_AND_NULL(msg);
2143 }
2144 out:
2145 if (this && buffer)
2146 repo_unuse_commit_buffer(r, this, buffer);
2147 free_commit_list(items);
2148 free(msg);
2149
2150 return res;
2151 }
2152
2153 static int import_stash(int argc, const char **argv, const char *prefix,
2154 struct repository *repo)
2155 {
2156 struct option options[] = {
2157 OPT_END()
2158 };
2159
2160 argc = parse_options(argc, argv, prefix, options,
2161 git_stash_import_usage,
2162 PARSE_OPT_KEEP_DASHDASH);
2163
2164 if (argc != 1)
2165 usage_msg_opt("a revision is required", git_stash_import_usage, options);
2166
2167 return do_import_stash(repo, argv[0]);
2168 }
2169
2170 struct stash_entry_data {
2171 struct repository *r;
2172 struct commit_list **items;
2173 size_t count;
2174 };
2175
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,
2181 void *cb_data)
2182 {
2183 struct stash_entry_data *data = cb_data;
2184 struct commit *stash;
2185
2186 data->count++;
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));
2191 }
2192 data->items = commit_list_append(stash, data->items);
2193 return 0;
2194 }
2195
2196 static int do_export_stash(struct repository *r,
2197 const char *ref,
2198 int argc,
2199 const char **argv)
2200 {
2201 struct object_id base;
2202 struct object_context unused;
2203 struct commit *prev;
2204 struct commit_list *items = NULL, **iter = &items, *cur;
2205 int res = 0;
2206 int i;
2207 struct strbuf revision = STRBUF_INIT;
2208 const char *author, *committer;
2209
2210 /*
2211 * This is an arbitrary, fixed date, specifically the one used by git
2212 * format-patch. The goal is merely to produce reproducible output.
2213 */
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);
2219
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"));
2224
2225 prev = lookup_commit_reference(r, &base);
2226
2227 if (argc) {
2228 /*
2229 * Find each specified stash, and load data into the array.
2230 */
2231 for (i = 0; i < argc; i++) {
2232 struct object_id oid;
2233 struct commit *stash;
2234
2235 if (parse_stash_revision(&revision, argv[i], 1) ||
2236 get_oid_with_context(r, revision.buf,
2237 GET_OID_QUIETLY | GET_OID_GENTLY,
2238 &oid, &unused)) {
2239 res = error(_("unable to find stash entry %s"), argv[i]);
2240 goto out;
2241 }
2242
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"),
2246 revision.buf);
2247 goto out;
2248 }
2249 iter = commit_list_append(stash, iter);
2250 }
2251 } else {
2252 /*
2253 * Walk the reflog, finding each stash entry, and load data into the
2254 * array.
2255 */
2256 struct stash_entry_data cb_data = {
2257 .r = r, .items = iter,
2258 };
2259 if (refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
2260 "refs/stash",
2261 collect_stash_entries,
2262 &cb_data) && cb_data.count)
2263 goto out;
2264 }
2265
2266 /*
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
2269 * base commit.
2270 */
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;
2277
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);
2282 if (res)
2283 goto out;
2284 prev = lookup_commit_reference(r, &out);
2285 }
2286 if (ref)
2287 refs_update_ref(get_main_ref_store(r), NULL, ref,
2288 &prev->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
2289 else
2290 puts(oid_to_hex(&prev->object.oid));
2291 out:
2292 strbuf_release(&revision);
2293 free_commit_list(items);
2294
2295 return res;
2296 }
2297
2298 enum export_action {
2299 ACTION_NONE,
2300 ACTION_PRINT,
2301 ACTION_TO_REF,
2302 };
2303
2304 static int export_stash(int argc,
2305 const char **argv,
2306 const char *prefix,
2307 struct repository *repo)
2308 {
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"),
2314 ACTION_PRINT),
2315 OPT_STRING(0, "to-ref", &ref, "ref",
2316 N_("save the data to the given ref")),
2317 OPT_END()
2318 };
2319
2320 argc = parse_options(argc, argv, prefix, options,
2321 git_stash_export_usage,
2322 PARSE_OPT_KEEP_DASHDASH);
2323
2324 if (ref && action == ACTION_NONE)
2325 action = ACTION_TO_REF;
2326
2327 if (action == ACTION_NONE || (ref && action == ACTION_PRINT))
2328 return error(_("exactly one of --print and --to-ref is required"));
2329
2330 return do_export_stash(repo, ref, argc, argv);
2331 }
2332
2333 int cmd_stash(int argc,
2334 const char **argv,
2335 const char *prefix,
2336 struct repository *repo)
2337 {
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),
2356 OPT_END()
2357 };
2358 const char **args_copy;
2359 int ret;
2360
2361 git_config(git_stash_config, NULL);
2362
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);
2367
2368 prepare_repo_settings(the_repository);
2369 the_repository->settings.command_requires_full_index = 0;
2370
2371 index_file = repo_get_index_file(the_repository);
2372 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
2373 (uintmax_t)pid);
2374
2375 if (fn)
2376 return !!fn(argc, argv, prefix, repo);
2377 else if (!argc)
2378 return !!push_stash_unassumed(0, NULL, prefix, repo);
2379
2380 /* Assume 'stash push' */
2381 strvec_push(&args, "push");
2382 strvec_pushv(&args, argv);
2383
2384 /*
2385 * `push_stash()` ends up modifying the array, which causes memory
2386 * leaks if we didn't copy the array here.
2387 */
2388 DUP_ARRAY(args_copy, args.v, args.nr);
2389
2390 ret = !!push_stash(args.nr, args_copy, prefix, 1);
2391
2392 strvec_clear(&args);
2393 free(args_copy);
2394 return ret;
2395 }