Raw
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] [--label-ours=<label>] [--label-theirs=<label>] [--label-base=<label>] [<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 static int show_stat = 1;
150 static int show_patch;
151 static int show_include_untracked;
152 static int use_index;
153
154 /*
155 * w_commit is set to the commit containing the working tree
156 * b_commit is set to the base commit
157 * i_commit is set to the commit containing the index tree
158 * u_commit is set to the commit containing the untracked files tree
159 * c_commit is set to the first parent (chain commit) when importing and is otherwise unset
160 * w_tree is set to the working tree
161 * b_tree is set to the base tree
162 * i_tree is set to the index tree
163 * u_tree is set to the untracked files tree
164 */
165 struct stash_info {
166 struct object_id w_commit;
167 struct object_id b_commit;
168 struct object_id i_commit;
169 struct object_id u_commit;
170 struct object_id c_commit;
171 struct object_id w_tree;
172 struct object_id b_tree;
173 struct object_id i_tree;
174 struct object_id u_tree;
175 struct strbuf revision;
176 int is_stash_ref;
177 int has_u;
178 };
179
180 #define STASH_INFO_INIT { \
181 .revision = STRBUF_INIT, \
182 }
183
184 static void free_stash_info(struct stash_info *info)
185 {
186 strbuf_release(&info->revision);
187 }
188
189 static int check_stash_topology(struct repository *r, struct commit *stash)
190 {
191 struct commit *p1, *p2, *p3 = NULL;
192
193 /* stash must have two or three parents */
194 if (!stash->parents || !stash->parents->next ||
195 (stash->parents->next->next && stash->parents->next->next->next))
196 return -1;
197 p1 = stash->parents->item;
198 p2 = stash->parents->next->item;
199 if (stash->parents->next->next)
200 p3 = stash->parents->next->next->item;
201 if (repo_parse_commit(r, p1) || repo_parse_commit(r, p2) ||
202 (p3 && repo_parse_commit(r, p3)))
203 return -1;
204 /* p2 must have a single parent, p3 must have no parents */
205 if (!p2->parents || p2->parents->next || (p3 && p3->parents))
206 return -1;
207 if (repo_parse_commit(r, p2->parents->item))
208 return -1;
209 /* p2^1 must equal p1 */
210 if (!oideq(&p1->object.oid, &p2->parents->item->object.oid))
211 return -1;
212
213 return 0;
214 }
215
216 static void assert_stash_like(struct stash_info *info, const char *revision)
217 {
218 if (get_oidf(&info->b_commit, "%s^1", revision) ||
219 get_oidf(&info->w_tree, "%s:", revision) ||
220 get_oidf(&info->b_tree, "%s^1:", revision) ||
221 get_oidf(&info->i_tree, "%s^2:", revision))
222 die(_("'%s' is not a stash-like commit"), revision);
223 }
224
225 static int parse_stash_revision(struct strbuf *revision, const char *commit, int quiet)
226 {
227 strbuf_reset(revision);
228 if (!commit) {
229 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash)) {
230 if (!quiet)
231 fprintf_ln(stderr, _("No stash entries found."));
232 return -1;
233 }
234
235 strbuf_addf(revision, "%s@{0}", ref_stash);
236 } else if (strspn(commit, "0123456789") == strlen(commit)) {
237 strbuf_addf(revision, "%s@{%s}", ref_stash, commit);
238 } else {
239 strbuf_addstr(revision, commit);
240 }
241 return 0;
242 }
243
244 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
245 {
246 int ret;
247 char *end_of_rev;
248 char *expanded_ref;
249 const char *revision;
250 const char *commit = NULL;
251 struct object_id dummy;
252 struct strbuf symbolic = STRBUF_INIT;
253
254 if (argc > 1) {
255 int i;
256 struct strbuf refs_msg = STRBUF_INIT;
257
258 for (i = 0; i < argc; i++)
259 strbuf_addf(&refs_msg, " '%s'", argv[i]);
260
261 fprintf_ln(stderr, _("Too many revisions specified:%s"),
262 refs_msg.buf);
263 strbuf_release(&refs_msg);
264
265 return -1;
266 }
267
268 if (argc == 1)
269 commit = argv[0];
270
271 strbuf_init(&info->revision, 0);
272 if (parse_stash_revision(&info->revision, commit, 0)) {
273 return -1;
274 }
275
276 revision = info->revision.buf;
277
278 if (repo_get_oid(the_repository, revision, &info->w_commit))
279 return error(_("%s is not a valid reference"), revision);
280
281 assert_stash_like(info, revision);
282
283 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
284
285 end_of_rev = strchrnul(revision, '@');
286 strbuf_add(&symbolic, revision, end_of_rev - revision);
287
288 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
289 &dummy, &expanded_ref, 0);
290 strbuf_release(&symbolic);
291 switch (ret) {
292 case 0: /* Not found, but valid ref */
293 info->is_stash_ref = 0;
294 break;
295 case 1:
296 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
297 break;
298 default: /* Invalid or ambiguous */
299 break;
300 }
301
302 free(expanded_ref);
303 return !(ret == 0 || ret == 1);
304 }
305
306 static int do_clear_stash(void)
307 {
308 struct object_id obj;
309 if (repo_get_oid(the_repository, ref_stash, &obj))
310 return 0;
311
312 return refs_delete_ref(get_main_ref_store(the_repository), NULL,
313 ref_stash, &obj, 0);
314 }
315
316 static int clear_stash(int argc, const char **argv, const char *prefix,
317 struct repository *repo UNUSED)
318 {
319 struct option options[] = {
320 OPT_END()
321 };
322
323 argc = parse_options(argc, argv, prefix, options,
324 git_stash_clear_usage,
325 PARSE_OPT_STOP_AT_NON_OPTION);
326
327 if (argc)
328 return error(_("git stash clear with arguments is "
329 "unimplemented"));
330
331 return do_clear_stash();
332 }
333
334 static int reset_tree(struct object_id *i_tree, int update, int reset)
335 {
336 int nr_trees = 1;
337 struct unpack_trees_options opts;
338 struct tree_desc t[MAX_UNPACK_TREES];
339 struct tree *tree;
340 struct lock_file lock_file = LOCK_INIT;
341
342 repo_read_index_preload(the_repository, NULL, 0);
343 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
344 return -1;
345
346 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
347
348 memset(&opts, 0, sizeof(opts));
349
350 tree = repo_parse_tree_indirect(the_repository, i_tree);
351 if (repo_parse_tree(the_repository, tree))
352 return -1;
353
354 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
355
356 opts.head_idx = 1;
357 opts.src_index = the_repository->index;
358 opts.dst_index = the_repository->index;
359 opts.merge = 1;
360 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
361 opts.update = update;
362 if (update)
363 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
364 opts.fn = oneway_merge;
365
366 if (unpack_trees(nr_trees, t, &opts))
367 return -1;
368
369 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
370 return error(_("unable to write new index file"));
371
372 return 0;
373 }
374
375 static int create_index_from_tree(const struct object_id *tree_id,
376 const char *index_path)
377 {
378 int nr_trees = 1;
379 int ret = 0;
380 struct unpack_trees_options opts;
381 struct tree_desc t[MAX_UNPACK_TREES];
382 struct tree *tree;
383 struct index_state dst_istate = INDEX_STATE_INIT(the_repository);
384 struct lock_file lock_file = LOCK_INIT;
385
386 repo_read_index_preload(the_repository, NULL, 0);
387 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
388
389 hold_lock_file_for_update(&lock_file, index_path, LOCK_DIE_ON_ERROR);
390
391 memset(&opts, 0, sizeof(opts));
392
393 tree = repo_parse_tree_indirect(the_repository, tree_id);
394 if (!tree || repo_parse_tree(the_repository, tree)) {
395 ret = -1;
396 goto done;
397 }
398
399 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
400
401 opts.head_idx = 1;
402 opts.src_index = the_repository->index;
403 opts.dst_index = &dst_istate;
404 opts.merge = 1;
405 opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
406 opts.fn = oneway_merge;
407
408 if (unpack_trees(nr_trees, t, &opts)) {
409 ret = -1;
410 goto done;
411 }
412
413 if (write_locked_index(&dst_istate, &lock_file, COMMIT_LOCK)) {
414 ret = error(_("unable to write new index file"));
415 goto done;
416 }
417
418 done:
419 release_index(&dst_istate);
420 if (ret)
421 rollback_lock_file(&lock_file);
422 return ret;
423 }
424
425 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
426 {
427 struct child_process cp = CHILD_PROCESS_INIT;
428 const char *w_commit_hex = oid_to_hex(w_commit);
429
430 /*
431 * Diff-tree would not be very hard to replace with a native function,
432 * however it should be done together with apply_cached.
433 */
434 cp.git_cmd = 1;
435 strvec_pushl(&cp.args, "diff-tree", "--binary", "--no-color", NULL);
436 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
437
438 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
439 }
440
441 static int apply_cached(struct strbuf *out)
442 {
443 struct child_process cp = CHILD_PROCESS_INIT;
444
445 /*
446 * Apply currently only reads either from stdin or a file, thus
447 * apply_all_patches would have to be updated to optionally take a
448 * buffer.
449 */
450 cp.git_cmd = 1;
451 strvec_pushl(&cp.args, "apply", "--cached", NULL);
452 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
453 }
454
455 static int reset_head(void)
456 {
457 struct child_process cp = CHILD_PROCESS_INIT;
458
459 /*
460 * Reset is overall quite simple, however there is no current public
461 * API for resetting.
462 */
463 cp.git_cmd = 1;
464 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
465
466 return run_command(&cp);
467 }
468
469 static int is_path_a_directory(const char *path)
470 {
471 /*
472 * This function differs from abspath.c:is_directory() in that
473 * here we use lstat() instead of stat(); we do not want to
474 * follow symbolic links here.
475 */
476 struct stat st;
477 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
478 }
479
480 static void add_diff_to_buf(struct diff_queue_struct *q,
481 struct diff_options *options UNUSED,
482 void *data)
483 {
484 int i;
485
486 for (i = 0; i < q->nr; i++) {
487 if (is_path_a_directory(q->queue[i]->one->path))
488 continue;
489
490 strbuf_addstr(data, q->queue[i]->one->path);
491
492 /* NUL-terminate: will be fed to update-index -z */
493 strbuf_addch(data, '\0');
494 }
495 }
496
497 static int restore_untracked(struct object_id *u_tree)
498 {
499 int res;
500 struct child_process cp = CHILD_PROCESS_INIT;
501
502 /*
503 * We need to run restore files from a given index, but without
504 * affecting the current index, so we use GIT_INDEX_FILE with
505 * run_command to fork processes that will not interfere.
506 */
507 cp.git_cmd = 1;
508 strvec_push(&cp.args, "read-tree");
509 strvec_push(&cp.args, oid_to_hex(u_tree));
510 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
511 stash_index_path.buf);
512 if (run_command(&cp)) {
513 remove_path(stash_index_path.buf);
514 return -1;
515 }
516
517 child_process_init(&cp);
518 cp.git_cmd = 1;
519 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
520 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
521 stash_index_path.buf);
522
523 res = run_command(&cp);
524 remove_path(stash_index_path.buf);
525 return res;
526 }
527
528 static void unstage_changes_unless_new(struct object_id *orig_tree)
529 {
530 /*
531 * When we enter this function, there has been a clean merge of
532 * relevant trees, and the merge logic always stages whatever merges
533 * cleanly. We want to unstage those changes, unless it corresponds
534 * to a file that didn't exist as of orig_tree.
535 *
536 * However, if any SKIP_WORKTREE path is modified relative to
537 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
538 * it to the worktree before unstaging.
539 */
540
541 struct checkout state = CHECKOUT_INIT;
542 struct diff_options diff_opts;
543 struct lock_file lock = LOCK_INIT;
544 int i;
545
546 /* If any entries have skip_worktree set, we'll have to check 'em out */
547 state.force = 1;
548 state.quiet = 1;
549 state.refresh_cache = 1;
550 state.istate = the_repository->index;
551
552 /*
553 * Step 1: get a difference between orig_tree (which corresponding
554 * to the index before a merge was run) and the current index
555 * (reflecting the changes brought in by the merge).
556 */
557 repo_diff_setup(the_repository, &diff_opts);
558 diff_opts.flags.recursive = 1;
559 diff_opts.detect_rename = 0;
560 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
561 diff_setup_done(&diff_opts);
562
563 do_diff_cache(orig_tree, &diff_opts);
564 diffcore_std(&diff_opts);
565
566 /* Iterate over the paths that changed due to the merge... */
567 for (i = 0; i < diff_queued_diff.nr; i++) {
568 struct diff_filepair *p;
569 struct cache_entry *ce;
570 int pos;
571
572 /* Look up the path's position in the current index. */
573 p = diff_queued_diff.queue[i];
574 pos = index_name_pos(the_repository->index, p->two->path,
575 strlen(p->two->path));
576
577 /*
578 * Step 2: Place changes in the working tree
579 *
580 * Stash is about restoring changes *to the working tree*.
581 * So if the merge successfully got a new version of some
582 * path, but left it out of the working tree, then clear the
583 * SKIP_WORKTREE bit and write it to the working tree.
584 */
585 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
586 struct stat st;
587
588 ce = the_repository->index->cache[pos];
589 if (!lstat(ce->name, &st)) {
590 /* Conflicting path present; relocate it */
591 struct strbuf new_path = STRBUF_INIT;
592 int fd;
593
594 strbuf_addf(&new_path,
595 "%s.stash.XXXXXX", ce->name);
596 fd = xmkstemp(new_path.buf);
597 close(fd);
598 printf(_("WARNING: Untracked file in way of "
599 "tracked file! Renaming\n "
600 " %s -> %s\n"
601 " to make room.\n"),
602 ce->name, new_path.buf);
603 if (rename(ce->name, new_path.buf))
604 die("Failed to move %s to %s",
605 ce->name, new_path.buf);
606 strbuf_release(&new_path);
607 }
608 checkout_entry(ce, &state, NULL, NULL);
609 ce->ce_flags &= ~CE_SKIP_WORKTREE;
610 }
611
612 /*
613 * Step 3: "unstage" changes, as long as they are still tracked
614 */
615 if (p->one->oid_valid) {
616 /*
617 * Path existed in orig_tree; restore index entry
618 * from that tree in order to "unstage" the changes.
619 */
620 int option = ADD_CACHE_OK_TO_REPLACE;
621 if (pos < 0)
622 option = ADD_CACHE_OK_TO_ADD;
623
624 ce = make_cache_entry(the_repository->index,
625 p->one->mode,
626 &p->one->oid,
627 p->one->path,
628 0, 0);
629 add_index_entry(the_repository->index, ce, option);
630 }
631 }
632 diff_flush(&diff_opts);
633
634 /*
635 * Step 4: write the new index to disk
636 */
637 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
638 if (write_locked_index(the_repository->index, &lock,
639 COMMIT_LOCK | SKIP_IF_UNCHANGED))
640 die(_("could not write index"));
641 }
642
643 static int do_apply_stash(const char *prefix, struct stash_info *info,
644 int index, int quiet,
645 const char *label_ours, const char *label_theirs,
646 const char *label_base)
647 {
648 int clean, ret;
649 int has_index = index;
650 struct merge_options o;
651 struct object_id c_tree;
652 struct object_id index_tree;
653 struct tree *head, *merge, *merge_base;
654 struct lock_file lock = LOCK_INIT;
655
656 repo_read_index_preload(the_repository, NULL, 0);
657 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
658 NULL, NULL, NULL))
659 return error(_("could not write index"));
660
661 if (write_index_as_tree(&c_tree, the_repository->index,
662 repo_get_index_file(the_repository), 0, NULL))
663 return error(_("cannot apply a stash in the middle of a merge"));
664
665 if (index) {
666 if (oideq(&info->b_tree, &info->i_tree) ||
667 oideq(&c_tree, &info->i_tree)) {
668 has_index = 0;
669 } else {
670 struct strbuf out = STRBUF_INIT;
671
672 if (diff_tree_binary(&out, &info->w_commit)) {
673 strbuf_release(&out);
674 return error(_("could not generate diff %s^!."),
675 oid_to_hex(&info->w_commit));
676 }
677
678 ret = apply_cached(&out);
679 strbuf_release(&out);
680 if (ret)
681 return error(_("conflicts in index. "
682 "Try without --index."));
683
684 discard_index(the_repository->index);
685 repo_read_index(the_repository);
686 if (write_index_as_tree(&index_tree, the_repository->index,
687 repo_get_index_file(the_repository), 0, NULL))
688 return error(_("could not save index tree"));
689
690 reset_head();
691 discard_index(the_repository->index);
692 repo_read_index(the_repository);
693 }
694 }
695
696 init_ui_merge_options(&o, the_repository);
697
698 o.branch1 = label_ours ? label_ours : "Updated upstream";
699 o.branch2 = label_theirs ? label_theirs : "Stashed changes";
700 o.ancestor = label_base ? label_base : "Stash base";
701
702 if (oideq(&info->b_tree, &c_tree))
703 o.branch1 = "Version stash was based on";
704
705 if (quiet)
706 o.verbosity = 0;
707
708 if (o.verbosity >= 3)
709 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
710
711 head = lookup_tree(o.repo, &c_tree);
712 merge = lookup_tree(o.repo, &info->w_tree);
713 merge_base = lookup_tree(o.repo, &info->b_tree);
714
715 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
716 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
717
718 /*
719 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
720 * merge was clean, and nonzero if the merge was unclean or encountered
721 * an error.
722 */
723 ret = clean >= 0 ? !clean : clean;
724
725 if (ret < 0)
726 rollback_lock_file(&lock);
727 else if (write_locked_index(o.repo->index, &lock,
728 COMMIT_LOCK | SKIP_IF_UNCHANGED))
729 ret = error(_("could not write index"));
730
731 if (ret) {
732 repo_rerere(the_repository, 0);
733
734 if (index)
735 fprintf_ln(stderr, _("Index was not unstashed."));
736
737 goto restore_untracked;
738 }
739
740 if (has_index) {
741 if (reset_tree(&index_tree, 0, 0))
742 ret = -1;
743 } else {
744 unstage_changes_unless_new(&c_tree);
745 }
746
747 restore_untracked:
748 if (info->has_u && restore_untracked(&info->u_tree))
749 ret = error(_("could not restore untracked files from stash"));
750
751 if (!quiet) {
752 struct child_process cp = CHILD_PROCESS_INIT;
753
754 /*
755 * Status is quite simple and could be replaced with calls to
756 * wt_status in the future, but it adds complexities which may
757 * require more tests.
758 */
759 cp.git_cmd = 1;
760 cp.dir = prefix;
761 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
762 absolute_path(repo_get_work_tree(the_repository)));
763 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
764 absolute_path(repo_get_git_dir(the_repository)));
765 strvec_push(&cp.args, "status");
766 run_command(&cp);
767 }
768
769 return ret;
770 }
771
772 static int apply_stash(int argc, const char **argv, const char *prefix,
773 struct repository *repo UNUSED)
774 {
775 int ret = -1;
776 int quiet = 0;
777 int index = use_index;
778 const char *label_ours = NULL, *label_theirs = NULL, *label_base = NULL;
779 struct stash_info info = STASH_INFO_INIT;
780 struct option options[] = {
781 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
782 OPT_BOOL(0, "index", &index,
783 N_("attempt to recreate the index")),
784 OPT_STRING(0, "label-ours", &label_ours, N_("label"),
785 N_("label for the upstream side in conflict markers")),
786 OPT_STRING(0, "label-theirs", &label_theirs, N_("label"),
787 N_("label for the stashed side in conflict markers")),
788 OPT_STRING(0, "label-base", &label_base, N_("label"),
789 N_("label for the base in diff3 conflict markers")),
790 OPT_END()
791 };
792
793 argc = parse_options(argc, argv, prefix, options,
794 git_stash_apply_usage, 0);
795
796 if (get_stash_info(&info, argc, argv))
797 goto cleanup;
798
799 ret = do_apply_stash(prefix, &info, index, quiet,
800 label_ours, label_theirs, label_base);
801 cleanup:
802 free_stash_info(&info);
803 return ret;
804 }
805
806 static int reject_reflog_ent(const char *refname UNUSED,
807 struct object_id *ooid UNUSED,
808 struct object_id *noid UNUSED,
809 const char *email UNUSED,
810 timestamp_t timestamp UNUSED,
811 int tz UNUSED, const char *message UNUSED,
812 void *cb_data UNUSED)
813 {
814 return 1;
815 }
816
817 static int reflog_is_empty(const char *refname)
818 {
819 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository),
820 refname, reject_reflog_ent, NULL);
821 }
822
823 static int do_drop_stash(struct stash_info *info, int quiet)
824 {
825 if (!reflog_delete(info->revision.buf,
826 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
827 0)) {
828 if (!quiet)
829 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
830 oid_to_hex(&info->w_commit));
831 } else {
832 return error(_("%s: Could not drop stash entry"),
833 info->revision.buf);
834 }
835
836 if (reflog_is_empty(ref_stash))
837 do_clear_stash();
838
839 return 0;
840 }
841
842 static int get_stash_info_assert(struct stash_info *info, int argc,
843 const char **argv)
844 {
845 int ret = get_stash_info(info, argc, argv);
846
847 if (ret < 0)
848 return ret;
849
850 if (!info->is_stash_ref)
851 return error(_("'%s' is not a stash reference"), info->revision.buf);
852
853 return 0;
854 }
855
856 static int drop_stash(int argc, const char **argv, const char *prefix,
857 struct repository *repo UNUSED)
858 {
859 int ret = -1;
860 int quiet = 0;
861 struct stash_info info = STASH_INFO_INIT;
862 struct option options[] = {
863 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
864 OPT_END()
865 };
866
867 argc = parse_options(argc, argv, prefix, options,
868 git_stash_drop_usage, 0);
869
870 if (get_stash_info_assert(&info, argc, argv))
871 goto cleanup;
872
873 ret = do_drop_stash(&info, quiet);
874 cleanup:
875 free_stash_info(&info);
876 return ret;
877 }
878
879 static int pop_stash(int argc, const char **argv, const char *prefix,
880 struct repository *repo UNUSED)
881 {
882 int ret = -1;
883 int index = use_index;
884 int quiet = 0;
885 struct stash_info info = STASH_INFO_INIT;
886 struct option options[] = {
887 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
888 OPT_BOOL(0, "index", &index,
889 N_("attempt to recreate the index")),
890 OPT_END()
891 };
892
893 argc = parse_options(argc, argv, prefix, options,
894 git_stash_pop_usage, 0);
895
896 if (get_stash_info_assert(&info, argc, argv))
897 goto cleanup;
898
899 if ((ret = do_apply_stash(prefix, &info, index, quiet,
900 NULL, NULL, NULL)))
901 printf_ln(_("The stash entry is kept in case "
902 "you need it again."));
903 else
904 ret = do_drop_stash(&info, quiet);
905
906 cleanup:
907 free_stash_info(&info);
908 return ret;
909 }
910
911 static int branch_stash(int argc, const char **argv, const char *prefix,
912 struct repository *repo UNUSED)
913 {
914 int ret = -1;
915 const char *branch = NULL;
916 struct stash_info info = STASH_INFO_INIT;
917 struct child_process cp = CHILD_PROCESS_INIT;
918 struct option options[] = {
919 OPT_END()
920 };
921
922 argc = parse_options(argc, argv, prefix, options,
923 git_stash_branch_usage, 0);
924
925 if (!argc) {
926 fprintf_ln(stderr, _("No branch name specified"));
927 return -1;
928 }
929
930 branch = argv[0];
931
932 if (get_stash_info(&info, argc - 1, argv + 1))
933 goto cleanup;
934
935 cp.git_cmd = 1;
936 strvec_pushl(&cp.args, "checkout", "-b", NULL);
937 strvec_push(&cp.args, branch);
938 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
939 ret = run_command(&cp);
940 if (!ret)
941 ret = do_apply_stash(prefix, &info, 1, 0,
942 NULL, NULL, NULL);
943 if (!ret && info.is_stash_ref)
944 ret = do_drop_stash(&info, 0);
945
946 cleanup:
947 free_stash_info(&info);
948 return ret;
949 }
950
951 static int list_stash(int argc, const char **argv, const char *prefix,
952 struct repository *repo UNUSED)
953 {
954 struct child_process cp = CHILD_PROCESS_INIT;
955 struct option options[] = {
956 OPT_END()
957 };
958
959 argc = parse_options(argc, argv, prefix, options,
960 git_stash_list_usage,
961 PARSE_OPT_KEEP_UNKNOWN_OPT);
962
963 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash))
964 return 0;
965
966 cp.git_cmd = 1;
967 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
968 "--first-parent", NULL);
969 strvec_pushv(&cp.args, argv);
970 strvec_push(&cp.args, ref_stash);
971 strvec_push(&cp.args, "--");
972 return run_command(&cp);
973 }
974
975 static int git_stash_config(const char *var, const char *value,
976 const struct config_context *ctx, void *cb)
977 {
978 if (!strcmp(var, "stash.showstat")) {
979 show_stat = git_config_bool(var, value);
980 return 0;
981 }
982 if (!strcmp(var, "stash.showpatch")) {
983 show_patch = git_config_bool(var, value);
984 return 0;
985 }
986 if (!strcmp(var, "stash.showincludeuntracked")) {
987 show_include_untracked = git_config_bool(var, value);
988 return 0;
989 }
990 if (!strcmp(var, "stash.index")) {
991 use_index = git_config_bool(var, value);
992 return 0;
993 }
994 return git_diff_basic_config(var, value, ctx, cb);
995 }
996
997 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
998 {
999 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
1000 struct tree *tree[ARRAY_SIZE(oid)];
1001 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
1002 struct unpack_trees_options unpack_tree_opt = { 0 };
1003
1004 for (size_t i = 0; i < ARRAY_SIZE(oid); i++) {
1005 tree[i] = repo_parse_tree_indirect(the_repository, oid[i]);
1006 if (repo_parse_tree(the_repository, tree[i]) < 0)
1007 die(_("failed to parse tree"));
1008 init_tree_desc(&tree_desc[i], &tree[i]->object.oid,
1009 tree[i]->buffer, tree[i]->size);
1010 }
1011
1012 unpack_tree_opt.head_idx = -1;
1013 unpack_tree_opt.src_index = the_repository->index;
1014 unpack_tree_opt.dst_index = the_repository->index;
1015 unpack_tree_opt.merge = 1;
1016 unpack_tree_opt.fn = stash_worktree_untracked_merge;
1017
1018 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
1019 die(_("failed to unpack trees"));
1020
1021 do_diff_cache(&info->b_commit, diff_opt);
1022 }
1023
1024 static int show_stash(int argc, const char **argv, const char *prefix,
1025 struct repository *repo UNUSED)
1026 {
1027 int i;
1028 int ret = -1;
1029 struct stash_info info = STASH_INFO_INIT;
1030 struct rev_info rev;
1031 struct strvec stash_args = STRVEC_INIT;
1032 struct strvec revision_args = STRVEC_INIT;
1033 enum {
1034 UNTRACKED_NONE,
1035 UNTRACKED_INCLUDE,
1036 UNTRACKED_ONLY
1037 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
1038 struct option options[] = {
1039 OPT_SET_INT('u', "include-untracked", &show_untracked,
1040 N_("include untracked files in the stash"),
1041 UNTRACKED_INCLUDE),
1042 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
1043 N_("only show untracked files in the stash"),
1044 UNTRACKED_ONLY, PARSE_OPT_NONEG),
1045 OPT_END()
1046 };
1047 int do_usage = 0;
1048
1049 init_diff_ui_defaults();
1050 repo_config(the_repository, git_diff_ui_config, NULL);
1051 repo_init_revisions(the_repository, &rev, prefix);
1052
1053 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
1054 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
1055 PARSE_OPT_KEEP_DASHDASH);
1056
1057 strvec_push(&revision_args, argv[0]);
1058 for (i = 1; i < argc; i++) {
1059 if (argv[i][0] != '-')
1060 strvec_push(&stash_args, argv[i]);
1061 else
1062 strvec_push(&revision_args, argv[i]);
1063 }
1064
1065 if (get_stash_info(&info, stash_args.nr, stash_args.v))
1066 goto cleanup;
1067
1068 /*
1069 * The config settings are applied only if there are not passed
1070 * any options.
1071 */
1072 if (revision_args.nr == 1) {
1073 if (show_stat)
1074 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
1075
1076 if (show_patch)
1077 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1078
1079 if (!show_stat && !show_patch) {
1080 ret = 0;
1081 goto cleanup;
1082 }
1083 }
1084
1085 setup_revisions_from_strvec(&revision_args, &rev, NULL);
1086 if (revision_args.nr > 1)
1087 goto usage;
1088 if (!rev.diffopt.output_format) {
1089 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
1090 diff_setup_done(&rev.diffopt);
1091 }
1092
1093 rev.diffopt.flags.recursive = 1;
1094 setup_diff_pager(&rev.diffopt);
1095 switch (show_untracked) {
1096 case UNTRACKED_NONE:
1097 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
1098 break;
1099 case UNTRACKED_ONLY:
1100 if (info.has_u)
1101 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
1102 break;
1103 case UNTRACKED_INCLUDE:
1104 if (info.has_u)
1105 diff_include_untracked(&info, &rev.diffopt);
1106 else
1107 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
1108 break;
1109 }
1110 log_tree_diff_flush(&rev);
1111
1112 ret = diff_result_code(&rev);
1113
1114 cleanup:
1115 strvec_clear(&revision_args);
1116 strvec_clear(&stash_args);
1117 free_stash_info(&info);
1118 release_revisions(&rev);
1119 if (do_usage)
1120 usage_with_options(git_stash_show_usage, options);
1121 return ret;
1122 usage:
1123 do_usage = 1;
1124 goto cleanup;
1125 }
1126
1127 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
1128 int quiet)
1129 {
1130 struct stash_info info;
1131 char revision[GIT_MAX_HEXSZ];
1132
1133 oid_to_hex_r(revision, w_commit);
1134 assert_stash_like(&info, revision);
1135
1136 if (!stash_msg)
1137 stash_msg = "Created via \"git stash store\".";
1138
1139 if (refs_update_ref(get_main_ref_store(the_repository), stash_msg, ref_stash, w_commit, NULL,
1140 REF_FORCE_CREATE_REFLOG,
1141 quiet ? UPDATE_REFS_QUIET_ON_ERR :
1142 UPDATE_REFS_MSG_ON_ERR)) {
1143 if (!quiet) {
1144 fprintf_ln(stderr, _("Cannot update %s with %s"),
1145 ref_stash, oid_to_hex(w_commit));
1146 }
1147 return -1;
1148 }
1149
1150 return 0;
1151 }
1152
1153 static int store_stash(int argc, const char **argv, const char *prefix,
1154 struct repository *repo UNUSED)
1155 {
1156 int quiet = 0;
1157 const char *stash_msg = NULL;
1158 struct object_id obj;
1159 struct option options[] = {
1160 OPT__QUIET(&quiet, N_("be quiet")),
1161 OPT_STRING('m', "message", &stash_msg, "message",
1162 N_("stash message")),
1163 OPT_END()
1164 };
1165 int ret;
1166
1167 argc = parse_options(argc, argv, prefix, options,
1168 git_stash_store_usage,
1169 PARSE_OPT_KEEP_UNKNOWN_OPT);
1170
1171 if (argc != 1) {
1172 if (!quiet)
1173 fprintf_ln(stderr, _("\"git stash store\" requires one "
1174 "<commit> argument"));
1175 return -1;
1176 }
1177
1178 if (repo_get_oid_with_flags(the_repository, argv[0], &obj,
1179 quiet ? GET_OID_QUIETLY : 0)) {
1180 if (!quiet)
1181 fprintf_ln(stderr, _("Cannot update %s with %s"),
1182 ref_stash, argv[0]);
1183 ret = -1;
1184 goto out;
1185 }
1186
1187 ret = do_store_stash(&obj, stash_msg, quiet);
1188
1189 out:
1190 return ret;
1191 }
1192
1193 static void add_pathspecs(struct strvec *args,
1194 const struct pathspec *ps) {
1195 int i;
1196
1197 for (i = 0; i < ps->nr; i++)
1198 strvec_push(args, ps->items[i].original);
1199 }
1200
1201 /*
1202 * `untracked_files` will be filled with the names of untracked files.
1203 * The return value is:
1204 *
1205 * = 0 if there are not any untracked files
1206 * > 0 if there are untracked files
1207 */
1208 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1209 struct strbuf *untracked_files)
1210 {
1211 int i;
1212 int found = 0;
1213 struct dir_struct dir = DIR_INIT;
1214
1215 if (include_untracked != INCLUDE_ALL_FILES)
1216 setup_standard_excludes(&dir);
1217
1218 fill_directory(&dir, the_repository->index, ps);
1219 for (i = 0; i < dir.nr; i++) {
1220 struct dir_entry *ent = dir.entries[i];
1221 found++;
1222 strbuf_addstr(untracked_files, ent->name);
1223 /* NUL-terminate: will be fed to update-index -z */
1224 strbuf_addch(untracked_files, '\0');
1225 }
1226
1227 dir_clear(&dir);
1228 return found;
1229 }
1230
1231 /*
1232 * The return value of `check_changes_tracked_files()` can be:
1233 *
1234 * < 0 if there was an error
1235 * = 0 if there are no changes.
1236 * > 0 if there are changes.
1237 */
1238 static int check_changes_tracked_files(const struct pathspec *ps)
1239 {
1240 struct rev_info rev;
1241 struct object_id dummy;
1242 int ret = 0;
1243
1244 /* No initial commit. */
1245 if (repo_get_oid(the_repository, "HEAD", &dummy))
1246 return -1;
1247
1248 if (repo_read_index(the_repository) < 0)
1249 return -1;
1250
1251 repo_init_revisions(the_repository, &rev, NULL);
1252 copy_pathspec(&rev.prune_data, ps);
1253
1254 rev.diffopt.flags.quick = 1;
1255 rev.diffopt.flags.ignore_submodules = 1;
1256 rev.abbrev = 0;
1257
1258 add_head_to_pending(&rev);
1259 diff_setup_done(&rev.diffopt);
1260
1261 run_diff_index(&rev, DIFF_INDEX_CACHED);
1262 if (diff_result_code(&rev)) {
1263 ret = 1;
1264 goto done;
1265 }
1266
1267 run_diff_files(&rev, 0);
1268 if (diff_result_code(&rev)) {
1269 ret = 1;
1270 goto done;
1271 }
1272
1273 done:
1274 release_revisions(&rev);
1275 return ret;
1276 }
1277
1278 /*
1279 * The function will fill `untracked_files` with the names of untracked files
1280 * It will return 1 if there were any changes and 0 if there were not.
1281 */
1282 static int check_changes(const struct pathspec *ps, int include_untracked,
1283 struct strbuf *untracked_files)
1284 {
1285 int ret = 0;
1286 if (check_changes_tracked_files(ps))
1287 ret = 1;
1288
1289 if (include_untracked && get_untracked_files(ps, include_untracked,
1290 untracked_files))
1291 ret = 1;
1292
1293 return ret;
1294 }
1295
1296 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1297 struct strbuf *files)
1298 {
1299 int ret = 0;
1300 struct strbuf untracked_msg = STRBUF_INIT;
1301 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1302 struct index_state istate = INDEX_STATE_INIT(the_repository);
1303
1304 cp_upd_index.git_cmd = 1;
1305 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1306 "--remove", "--stdin", NULL);
1307 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1308 stash_index_path.buf);
1309
1310 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1311 if (pipe_command(&cp_upd_index, files->buf, files->len, NULL, 0,
1312 NULL, 0)) {
1313 ret = -1;
1314 goto done;
1315 }
1316
1317 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1318 NULL)) {
1319 ret = -1;
1320 goto done;
1321 }
1322
1323 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1324 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1325 ret = -1;
1326 goto done;
1327 }
1328
1329 done:
1330 release_index(&istate);
1331 strbuf_release(&untracked_msg);
1332 remove_path(stash_index_path.buf);
1333 return ret;
1334 }
1335
1336 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1337 int quiet)
1338 {
1339 int ret = 0;
1340 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1341 struct index_state istate = INDEX_STATE_INIT(the_repository);
1342
1343 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1344 0, NULL)) {
1345 ret = -1;
1346 goto done;
1347 }
1348
1349 cp_diff_tree.git_cmd = 1;
1350 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "--binary",
1351 "--no-color",
1352 "-U1", "HEAD", oid_to_hex(&info->w_tree), "--", NULL);
1353 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1354 ret = -1;
1355 goto done;
1356 }
1357
1358 if (!out_patch->len) {
1359 if (!quiet)
1360 fprintf_ln(stderr, _("No staged changes"));
1361 ret = 1;
1362 }
1363
1364 done:
1365 release_index(&istate);
1366 return ret;
1367 }
1368
1369 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1370 struct strbuf *out_patch, int quiet,
1371 struct interactive_options *interactive_opts)
1372 {
1373 int ret = 0;
1374 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1375 struct commit *head_commit;
1376 const struct object_id *head_tree;
1377 struct index_state istate = INDEX_STATE_INIT(the_repository);
1378 char *old_index_env = NULL, *old_repo_index_file;
1379
1380 remove_path(stash_index_path.buf);
1381
1382 head_commit = lookup_commit(the_repository, &info->b_commit);
1383 if (!head_commit || repo_parse_commit(the_repository, head_commit)) {
1384 ret = -1;
1385 goto done;
1386 }
1387 head_tree = get_commit_tree_oid(head_commit);
1388 if (!head_tree) {
1389 ret = -1;
1390 goto done;
1391 }
1392
1393 if (create_index_from_tree(head_tree, stash_index_path.buf)) {
1394 ret = -1;
1395 goto done;
1396 }
1397
1398 /* Find out what the user wants. */
1399 old_repo_index_file = the_repository->index_file;
1400 the_repository->index_file = stash_index_path.buf;
1401 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1402 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1403
1404 ret = !!run_add_p(the_repository, ADD_P_STASH, interactive_opts, NULL, ps, 0);
1405
1406 the_repository->index_file = old_repo_index_file;
1407 if (old_index_env && *old_index_env)
1408 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1409 else
1410 unsetenv(INDEX_ENVIRONMENT);
1411 FREE_AND_NULL(old_index_env);
1412
1413 /* State of the working tree. */
1414 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1415 NULL)) {
1416 ret = -1;
1417 goto done;
1418 }
1419
1420 cp_diff_tree.git_cmd = 1;
1421 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1422 "--no-color",
1423 oid_to_hex(&info->w_tree), "--", NULL);
1424 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1425 ret = -1;
1426 goto done;
1427 }
1428
1429 if (!out_patch->len) {
1430 if (!quiet)
1431 fprintf_ln(stderr, _("No changes selected"));
1432 ret = 1;
1433 }
1434
1435 done:
1436 release_index(&istate);
1437 remove_path(stash_index_path.buf);
1438 return ret;
1439 }
1440
1441 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1442 {
1443 int ret = 0;
1444 struct rev_info rev;
1445 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1446 struct strbuf diff_output = STRBUF_INIT;
1447 struct index_state istate = INDEX_STATE_INIT(the_repository);
1448
1449 repo_init_revisions(the_repository, &rev, NULL);
1450 copy_pathspec(&rev.prune_data, ps);
1451
1452 set_alternate_index_output(stash_index_path.buf);
1453 if (reset_tree(&info->i_tree, 0, 0)) {
1454 ret = -1;
1455 goto done;
1456 }
1457 set_alternate_index_output(NULL);
1458
1459 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1460 rev.diffopt.format_callback = add_diff_to_buf;
1461 rev.diffopt.format_callback_data = &diff_output;
1462
1463 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1464 ret = -1;
1465 goto done;
1466 }
1467
1468 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1469 "");
1470 run_diff_index(&rev, 0);
1471
1472 cp_upd_index.git_cmd = 1;
1473 strvec_pushl(&cp_upd_index.args, "update-index",
1474 "--ignore-skip-worktree-entries",
1475 "-z", "--add", "--remove", "--stdin", NULL);
1476 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1477 stash_index_path.buf);
1478
1479 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1480 NULL, 0, NULL, 0)) {
1481 ret = -1;
1482 goto done;
1483 }
1484
1485 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1486 NULL)) {
1487 ret = -1;
1488 goto done;
1489 }
1490
1491 done:
1492 release_index(&istate);
1493 release_revisions(&rev);
1494 strbuf_release(&diff_output);
1495 remove_path(stash_index_path.buf);
1496 return ret;
1497 }
1498
1499 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1500 int include_untracked, int patch_mode,
1501 struct interactive_options *interactive_opts,
1502 int only_staged, struct stash_info *info, struct strbuf *patch,
1503 int quiet)
1504 {
1505 int ret = 0;
1506 int flags = 0;
1507 int untracked_commit_option = 0;
1508 const char *head_short_sha1 = NULL;
1509 const char *branch_ref = NULL;
1510 const char *branch_name = "(no branch)";
1511 char *branch_name_buf = NULL;
1512 struct commit *head_commit = NULL;
1513 struct commit_list *parents = NULL;
1514 struct strbuf msg = STRBUF_INIT;
1515 struct strbuf commit_tree_label = STRBUF_INIT;
1516 struct strbuf untracked_files = STRBUF_INIT;
1517
1518 prepare_fallback_ident("git stash", "git@stash");
1519
1520 repo_read_index_preload(the_repository, NULL, 0);
1521 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1522 NULL, NULL, NULL) < 0) {
1523 ret = error(_("could not write index"));
1524 goto done;
1525 }
1526
1527 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1528 if (!quiet)
1529 fprintf_ln(stderr, _("You do not have "
1530 "the initial commit yet"));
1531 ret = -1;
1532 goto done;
1533 } else {
1534 head_commit = lookup_commit(the_repository, &info->b_commit);
1535 }
1536
1537 if (!check_changes(ps, include_untracked, &untracked_files)) {
1538 ret = 1;
1539 goto done;
1540 }
1541
1542 branch_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1543 "HEAD", 0, NULL, &flags);
1544
1545 if (flags & REF_ISSYMREF) {
1546 if (skip_prefix(branch_ref, "refs/heads/", &branch_name))
1547 branch_name = branch_name_buf = xstrdup(branch_name);
1548 }
1549
1550 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1551 &head_commit->object.oid,
1552 DEFAULT_ABBREV);
1553 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1554 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1555
1556 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1557 commit_list_insert(head_commit, &parents);
1558 if (write_index_as_tree(&info->i_tree, the_repository->index,
1559 repo_get_index_file(the_repository), 0, NULL) ||
1560 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1561 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1562 if (!quiet)
1563 fprintf_ln(stderr, _("Cannot save the current "
1564 "index state"));
1565 ret = -1;
1566 goto done;
1567 }
1568
1569 commit_list_free(parents);
1570 parents = NULL;
1571
1572 if (include_untracked) {
1573 if (save_untracked_files(info, &msg, &untracked_files)) {
1574 if (!quiet)
1575 fprintf_ln(stderr, _("Cannot save "
1576 "the untracked files"));
1577 ret = -1;
1578 goto done;
1579 }
1580 untracked_commit_option = 1;
1581 }
1582 if (patch_mode) {
1583 ret = stash_patch(info, ps, patch, quiet, interactive_opts);
1584 if (ret < 0) {
1585 if (!quiet)
1586 fprintf_ln(stderr, _("Cannot save the current "
1587 "worktree state"));
1588 goto done;
1589 } else if (ret > 0) {
1590 goto done;
1591 }
1592 } else if (only_staged) {
1593 ret = stash_staged(info, patch, quiet);
1594 if (ret < 0) {
1595 if (!quiet)
1596 fprintf_ln(stderr, _("Cannot save the current "
1597 "staged state"));
1598 goto done;
1599 } else if (ret > 0) {
1600 goto done;
1601 }
1602 } else {
1603 if (stash_working_tree(info, ps)) {
1604 if (!quiet)
1605 fprintf_ln(stderr, _("Cannot save the current "
1606 "worktree state"));
1607 ret = -1;
1608 goto done;
1609 }
1610 }
1611
1612 if (!stash_msg_buf->len)
1613 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1614 else
1615 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1616
1617 if (untracked_commit_option)
1618 commit_list_insert(lookup_commit(the_repository,
1619 &info->u_commit),
1620 &parents);
1621 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1622 &parents);
1623 commit_list_insert(head_commit, &parents);
1624
1625 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1626 parents, &info->w_commit, NULL, NULL)) {
1627 if (!quiet)
1628 fprintf_ln(stderr, _("Cannot record "
1629 "working tree state"));
1630 ret = -1;
1631 goto done;
1632 }
1633
1634 done:
1635 strbuf_release(&commit_tree_label);
1636 strbuf_release(&msg);
1637 strbuf_release(&untracked_files);
1638 commit_list_free(parents);
1639 free(branch_name_buf);
1640 return ret;
1641 }
1642
1643 static int create_stash(int argc, const char **argv, const char *prefix UNUSED,
1644 struct repository *repo UNUSED)
1645 {
1646 int ret;
1647 struct strbuf stash_msg_buf = STRBUF_INIT;
1648 struct stash_info info = STASH_INFO_INIT;
1649 struct pathspec ps;
1650
1651 /* Starting with argv[1], since argv[0] is "create" */
1652 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1653
1654 memset(&ps, 0, sizeof(ps));
1655 if (!check_changes_tracked_files(&ps))
1656 return 0;
1657
1658 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, NULL, 0, &info,
1659 NULL, 0);
1660 if (!ret)
1661 printf_ln("%s", oid_to_hex(&info.w_commit));
1662
1663 free_stash_info(&info);
1664 strbuf_release(&stash_msg_buf);
1665 return ret;
1666 }
1667
1668 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1669 int keep_index, int patch_mode,
1670 struct interactive_options *interactive_opts,
1671 int include_untracked, int only_staged)
1672 {
1673 int ret = 0;
1674 struct stash_info info = STASH_INFO_INIT;
1675 struct strbuf patch = STRBUF_INIT;
1676 struct strbuf stash_msg_buf = STRBUF_INIT;
1677 struct strbuf untracked_files = STRBUF_INIT;
1678 struct strbuf out = STRBUF_INIT;
1679
1680 if (patch_mode && keep_index == -1)
1681 keep_index = 1;
1682
1683 if (patch_mode && include_untracked) {
1684 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1685 " or --all at the same time"));
1686 ret = -1;
1687 goto done;
1688 }
1689
1690 /* --patch overrides --staged */
1691 if (patch_mode)
1692 only_staged = 0;
1693
1694 if (only_staged && include_untracked) {
1695 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1696 " or --all at the same time"));
1697 ret = -1;
1698 goto done;
1699 }
1700
1701 repo_read_index_preload(the_repository, NULL, 0);
1702 if (!include_untracked && ps->nr) {
1703 char *ps_matched = xcalloc(ps->nr, 1);
1704
1705 if (pathspec_needs_expanded_index(the_repository->index, ps))
1706 ensure_full_index(the_repository->index);
1707 for (size_t i = 0; i < the_repository->index->cache_nr; i++)
1708 ce_path_match(the_repository->index, the_repository->index->cache[i], ps,
1709 ps_matched);
1710
1711 if (report_path_error(ps_matched, ps)) {
1712 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1713 ret = -1;
1714 free(ps_matched);
1715 goto done;
1716 }
1717 free(ps_matched);
1718 }
1719
1720 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1721 NULL, NULL, NULL)) {
1722 ret = error(_("could not write index"));
1723 goto done;
1724 }
1725
1726 if (!check_changes(ps, include_untracked, &untracked_files)) {
1727 if (!quiet)
1728 printf_ln(_("No local changes to save"));
1729 goto done;
1730 }
1731
1732 if (!refs_reflog_exists(get_main_ref_store(the_repository), ref_stash) && do_clear_stash()) {
1733 ret = -1;
1734 if (!quiet)
1735 fprintf_ln(stderr, _("Cannot initialize stash"));
1736 goto done;
1737 }
1738
1739 if (stash_msg)
1740 strbuf_addstr(&stash_msg_buf, stash_msg);
1741 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1742 interactive_opts, only_staged, &info, &patch, quiet)) {
1743 ret = -1;
1744 goto done;
1745 }
1746
1747 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1748 ret = -1;
1749 if (!quiet)
1750 fprintf_ln(stderr, _("Cannot save the current status"));
1751 goto done;
1752 }
1753
1754 if (!quiet)
1755 printf_ln(_("Saved working directory and index state %s"),
1756 stash_msg_buf.buf);
1757
1758 if (!(patch_mode || only_staged)) {
1759 if (include_untracked && !ps->nr) {
1760 struct child_process cp = CHILD_PROCESS_INIT;
1761
1762 cp.git_cmd = 1;
1763 if (startup_info->original_cwd) {
1764 cp.dir = startup_info->original_cwd;
1765 strvec_pushf(&cp.env, "%s=%s",
1766 GIT_WORK_TREE_ENVIRONMENT,
1767 the_repository->worktree);
1768 }
1769 strvec_pushl(&cp.args, "clean", "--force",
1770 "--quiet", "-d", ":/", NULL);
1771 if (include_untracked == INCLUDE_ALL_FILES)
1772 strvec_push(&cp.args, "-x");
1773 if (run_command(&cp)) {
1774 ret = -1;
1775 goto done;
1776 }
1777 }
1778 discard_index(the_repository->index);
1779 if (ps->nr) {
1780 struct child_process cp_add = CHILD_PROCESS_INIT;
1781 struct child_process cp_diff = CHILD_PROCESS_INIT;
1782 struct child_process cp_apply = CHILD_PROCESS_INIT;
1783
1784 cp_add.git_cmd = 1;
1785 strvec_push(&cp_add.args, "add");
1786 if (!include_untracked)
1787 strvec_push(&cp_add.args, "-u");
1788 if (include_untracked == INCLUDE_ALL_FILES)
1789 strvec_push(&cp_add.args, "--force");
1790 strvec_push(&cp_add.args, "--");
1791 add_pathspecs(&cp_add.args, ps);
1792 if (run_command(&cp_add)) {
1793 ret = -1;
1794 goto done;
1795 }
1796
1797 cp_diff.git_cmd = 1;
1798 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1799 "--no-color",
1800 "--cached", "--binary", "HEAD", "--",
1801 NULL);
1802 add_pathspecs(&cp_diff.args, ps);
1803 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1804 ret = -1;
1805 goto done;
1806 }
1807
1808 cp_apply.git_cmd = 1;
1809 strvec_pushl(&cp_apply.args, "apply", "--index",
1810 "-R", NULL);
1811 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1812 NULL, 0)) {
1813 ret = -1;
1814 goto done;
1815 }
1816 } else {
1817 struct child_process cp = CHILD_PROCESS_INIT;
1818 cp.git_cmd = 1;
1819 /* BUG: this nukes untracked files in the way */
1820 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1821 "--no-recurse-submodules", NULL);
1822 if (run_command(&cp)) {
1823 ret = -1;
1824 goto done;
1825 }
1826 }
1827
1828 /*
1829 * When keeping staged entries, we need to reset the working
1830 * directory to match the state of our index. This can be
1831 * skipped when the index is the empty tree, because there is
1832 * nothing to reset in that case:
1833 *
1834 * - When the index has any file, regardless of whether
1835 * staged or not, the tree cannot be empty by definition
1836 * and thus we enter the condition.
1837 *
1838 * - When the index has no files, the only thing we need to
1839 * care about is untracked files when `--include-untracked`
1840 * is given. But as we already execute git-clean(1) further
1841 * up to delete such untracked files we don't have to do
1842 * anything here, either.
1843 *
1844 * We thus skip calling git-checkout(1) in this case, also
1845 * because running it on an empty tree will cause it to fail
1846 * due to the pathspec not matching anything.
1847 */
1848 if (keep_index == 1 && !is_null_oid(&info.i_tree) &&
1849 !is_empty_tree_oid(&info.i_tree, the_repository->hash_algo)) {
1850 struct child_process cp = CHILD_PROCESS_INIT;
1851
1852 cp.git_cmd = 1;
1853 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1854 oid_to_hex(&info.i_tree), "--", NULL);
1855 if (!ps->nr)
1856 strvec_push(&cp.args, ":/");
1857 else
1858 add_pathspecs(&cp.args, ps);
1859 if (run_command(&cp)) {
1860 ret = -1;
1861 goto done;
1862 }
1863 }
1864 goto done;
1865 } else {
1866 struct child_process cp = CHILD_PROCESS_INIT;
1867
1868 cp.git_cmd = 1;
1869 strvec_pushl(&cp.args, "apply", "-R", NULL);
1870
1871 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1872 if (!quiet)
1873 fprintf_ln(stderr, _("Cannot remove "
1874 "worktree changes"));
1875 ret = -1;
1876 goto done;
1877 }
1878
1879 if (keep_index < 1) {
1880 struct child_process cp = CHILD_PROCESS_INIT;
1881
1882 cp.git_cmd = 1;
1883 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1884 NULL);
1885 add_pathspecs(&cp.args, ps);
1886 if (run_command(&cp)) {
1887 ret = -1;
1888 goto done;
1889 }
1890 }
1891 goto done;
1892 }
1893
1894 done:
1895 strbuf_release(&patch);
1896 strbuf_release(&out);
1897 free_stash_info(&info);
1898 strbuf_release(&stash_msg_buf);
1899 strbuf_release(&untracked_files);
1900 return ret;
1901 }
1902
1903 static int push_stash(int argc, const char **argv, const char *prefix,
1904 int push_assumed)
1905 {
1906 int force_assume = 0;
1907 int keep_index = -1;
1908 int only_staged = 0;
1909 int patch_mode = 0;
1910 int include_untracked = 0;
1911 int quiet = 0;
1912 int pathspec_file_nul = 0;
1913 const char *stash_msg = NULL;
1914 char *pathspec_from_file = NULL;
1915 struct pathspec ps;
1916 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
1917 struct option options[] = {
1918 OPT_BOOL('k', "keep-index", &keep_index,
1919 N_("keep index")),
1920 OPT_BOOL('S', "staged", &only_staged,
1921 N_("stash staged changes only")),
1922 OPT_BOOL('p', "patch", &patch_mode,
1923 N_("stash in patch mode")),
1924 OPT_BOOL(0, "auto-advance", &interactive_opts.auto_advance,
1925 N_("auto advance to the next file when selecting hunks interactively")),
1926 OPT_DIFF_UNIFIED(&interactive_opts.context),
1927 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
1928 OPT__QUIET(&quiet, N_("quiet mode")),
1929 OPT_BOOL('u', "include-untracked", &include_untracked,
1930 N_("include untracked files in stash")),
1931 OPT_SET_INT('a', "all", &include_untracked,
1932 N_("include ignore files"), 2),
1933 OPT_STRING('m', "message", &stash_msg, N_("message"),
1934 N_("stash message")),
1935 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1936 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1937 OPT_END()
1938 };
1939 int ret;
1940
1941 if (argc) {
1942 int flags = PARSE_OPT_KEEP_DASHDASH;
1943
1944 if (push_assumed)
1945 flags |= PARSE_OPT_STOP_AT_NON_OPTION;
1946
1947 argc = parse_options(argc, argv, prefix, options,
1948 push_assumed ? git_stash_usage :
1949 git_stash_push_usage, flags);
1950 force_assume |= patch_mode;
1951 }
1952
1953 if (argc) {
1954 if (!strcmp(argv[0], "--")) {
1955 argc--;
1956 argv++;
1957 } else if (push_assumed && !force_assume) {
1958 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1959 argv[0]);
1960 }
1961 }
1962
1963 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1964 prefix, argv);
1965
1966 if (pathspec_from_file) {
1967 if (patch_mode)
1968 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1969
1970 if (only_staged)
1971 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1972
1973 if (ps.nr)
1974 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1975
1976 parse_pathspec_file(&ps, 0,
1977 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1978 prefix, pathspec_from_file, pathspec_file_nul);
1979 } else if (pathspec_file_nul) {
1980 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1981 }
1982
1983 if (!patch_mode) {
1984 if (interactive_opts.context != -1)
1985 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
1986 if (interactive_opts.interhunkcontext != -1)
1987 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
1988 if (!interactive_opts.auto_advance)
1989 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
1990 }
1991
1992 if (interactive_opts.context < -1)
1993 die(_("'%s' cannot be negative"), "--unified");
1994 if (interactive_opts.interhunkcontext < -1)
1995 die(_("'%s' cannot be negative"), "--inter-hunk-context");
1996
1997 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1998 &interactive_opts, include_untracked, only_staged);
1999
2000 clear_pathspec(&ps);
2001 free(pathspec_from_file);
2002 return ret;
2003 }
2004
2005 static int push_stash_unassumed(int argc, const char **argv, const char *prefix,
2006 struct repository *repo UNUSED)
2007 {
2008 return push_stash(argc, argv, prefix, 0);
2009 }
2010
2011 static int save_stash(int argc, const char **argv, const char *prefix,
2012 struct repository *repo UNUSED)
2013 {
2014 int keep_index = -1;
2015 int only_staged = 0;
2016 int patch_mode = 0;
2017 int include_untracked = 0;
2018 int quiet = 0;
2019 int ret = 0;
2020 const char *stash_msg = NULL;
2021 struct pathspec ps;
2022 struct strbuf stash_msg_buf = STRBUF_INIT;
2023 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
2024 struct option options[] = {
2025 OPT_BOOL('k', "keep-index", &keep_index,
2026 N_("keep index")),
2027 OPT_BOOL('S', "staged", &only_staged,
2028 N_("stash staged changes only")),
2029 OPT_BOOL('p', "patch", &patch_mode,
2030 N_("stash in patch mode")),
2031 OPT_BOOL(0, "auto-advance", &interactive_opts.auto_advance,
2032 N_("auto advance to the next file when selecting hunks interactively")),
2033 OPT_DIFF_UNIFIED(&interactive_opts.context),
2034 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
2035 OPT__QUIET(&quiet, N_("quiet mode")),
2036 OPT_BOOL('u', "include-untracked", &include_untracked,
2037 N_("include untracked files in stash")),
2038 OPT_SET_INT('a', "all", &include_untracked,
2039 N_("include ignore files"), 2),
2040 OPT_STRING('m', "message", &stash_msg, "message",
2041 N_("stash message")),
2042 OPT_END()
2043 };
2044
2045 argc = parse_options(argc, argv, prefix, options,
2046 git_stash_save_usage,
2047 PARSE_OPT_KEEP_DASHDASH);
2048
2049 if (argc)
2050 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
2051
2052 memset(&ps, 0, sizeof(ps));
2053
2054 if (interactive_opts.context < -1)
2055 die(_("'%s' cannot be negative"), "--unified");
2056 if (interactive_opts.interhunkcontext < -1)
2057 die(_("'%s' cannot be negative"), "--inter-hunk-context");
2058
2059 if (!patch_mode) {
2060 if (interactive_opts.context != -1)
2061 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
2062 if (interactive_opts.interhunkcontext != -1)
2063 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
2064 if (!interactive_opts.auto_advance)
2065 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
2066 }
2067
2068 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
2069 patch_mode, &interactive_opts, include_untracked,
2070 only_staged);
2071
2072 strbuf_release(&stash_msg_buf);
2073 return ret;
2074 }
2075
2076 static int write_commit_with_parents(struct repository *r,
2077 struct object_id *out,
2078 const struct object_id *oid,
2079 struct commit_list *parents)
2080 {
2081 size_t author_len, committer_len;
2082 struct commit *this;
2083 const char *orig_author, *orig_committer;
2084 char *author = NULL, *committer = NULL;
2085 const char *buffer;
2086 unsigned long bufsize;
2087 const char *p;
2088 struct strbuf msg = STRBUF_INIT;
2089 int ret = 0;
2090 struct ident_split id;
2091
2092 this = lookup_commit_reference(r, oid);
2093 buffer = repo_get_commit_buffer(r, this, &bufsize);
2094 orig_author = find_commit_header(buffer, "author", &author_len);
2095 orig_committer = find_commit_header(buffer, "committer", &committer_len);
2096
2097 if (!orig_author || !orig_committer) {
2098 ret = error(_("cannot parse commit %s"), oid_to_hex(oid));
2099 goto out;
2100 }
2101
2102 if (split_ident_line(&id, orig_author, author_len) < 0 ||
2103 split_ident_line(&id, orig_committer, committer_len) < 0) {
2104 ret = error(_("invalid author or committer for %s"), oid_to_hex(oid));
2105 goto out;
2106 }
2107
2108 p = strstr(buffer, "\n\n");
2109 strbuf_addstr(&msg, "git stash: ");
2110
2111 if (p)
2112 strbuf_add(&msg, p + 2, bufsize - (p + 2 - buffer));
2113 strbuf_complete_line(&msg);
2114
2115 author = xmemdupz(orig_author, author_len);
2116 committer = xmemdupz(orig_committer, committer_len);
2117
2118 if (commit_tree_extended(msg.buf, msg.len,
2119 r->hash_algo->empty_tree, parents,
2120 out, author, committer,
2121 NULL, NULL)) {
2122 ret = error(_("could not write commit"));
2123 goto out;
2124 }
2125 out:
2126 strbuf_release(&msg);
2127 repo_unuse_commit_buffer(r, this, buffer);
2128 free(author);
2129 free(committer);
2130 return ret;
2131 }
2132
2133 static int do_import_stash(struct repository *r, const char *rev)
2134 {
2135 struct object_id chain;
2136 int res = 0;
2137 const char *buffer = NULL;
2138 unsigned long bufsize;
2139 struct commit *this = NULL;
2140 struct commit_list *items = NULL, *cur;
2141 char *msg = NULL;
2142
2143 if (repo_get_oid(r, rev, &chain))
2144 return error(_("not a valid revision: %s"), rev);
2145
2146 this = lookup_commit_reference(r, &chain);
2147 if (!this)
2148 return error(_("not a commit: %s"), rev);
2149
2150 /*
2151 * Walk the commit history, finding each stash entry, and load data into
2152 * the array.
2153 */
2154 for (;;) {
2155 const char *author, *committer;
2156 size_t author_len, committer_len;
2157 const char *p;
2158 const char *expected = "git stash <git@stash> 1000684800 +0000";
2159 const char *prefix = "git stash: ";
2160 struct commit *stash;
2161 struct tree *tree = repo_get_commit_tree(r, this);
2162
2163 if (!tree ||
2164 !oideq(&tree->object.oid, r->hash_algo->empty_tree) ||
2165 (this->parents &&
2166 (!this->parents->next || this->parents->next->next))) {
2167 res = error(_("%s is not a valid exported stash commit"),
2168 oid_to_hex(&this->object.oid));
2169 goto out;
2170 }
2171
2172 buffer = repo_get_commit_buffer(r, this, &bufsize);
2173
2174 if (!this->parents) {
2175 /*
2176 * We don't have any parents. Make sure this is our
2177 * root commit.
2178 */
2179 author = find_commit_header(buffer, "author", &author_len);
2180 committer = find_commit_header(buffer, "committer", &committer_len);
2181
2182 if (!author || !committer) {
2183 error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2184 goto out;
2185 }
2186
2187 if (author_len != strlen(expected) ||
2188 committer_len != strlen(expected) ||
2189 memcmp(author, expected, author_len) ||
2190 memcmp(committer, expected, committer_len)) {
2191 res = error(_("found root commit %s with invalid data"), oid_to_hex(&this->object.oid));
2192 goto out;
2193 }
2194 break;
2195 }
2196
2197 p = strstr(buffer, "\n\n");
2198 if (!p) {
2199 res = error(_("cannot parse commit %s"), oid_to_hex(&this->object.oid));
2200 goto out;
2201 }
2202
2203 p += 2;
2204 if (((size_t)(bufsize - (p - buffer)) < strlen(prefix)) ||
2205 memcmp(prefix, p, strlen(prefix))) {
2206 res = error(_("found stash commit %s without expected prefix"), oid_to_hex(&this->object.oid));
2207 goto out;
2208 }
2209
2210 stash = this->parents->next->item;
2211
2212 if (repo_parse_commit(r, this->parents->item) ||
2213 repo_parse_commit(r, stash)) {
2214 res = error(_("cannot parse parents of commit: %s"),
2215 oid_to_hex(&this->object.oid));
2216 goto out;
2217 }
2218
2219 if (check_stash_topology(r, stash)) {
2220 res = error(_("%s does not look like a stash commit"),
2221 oid_to_hex(&stash->object.oid));
2222 goto out;
2223 }
2224
2225 repo_unuse_commit_buffer(r, this, buffer);
2226 buffer = NULL;
2227 items = commit_list_insert(stash, &items);
2228 this = this->parents->item;
2229 }
2230
2231 /*
2232 * Now, walk each entry, adding it to the stash as a normal stash
2233 * commit.
2234 */
2235 for (cur = items; cur; cur = cur->next) {
2236 const char *p;
2237 struct object_id *oid;
2238
2239 this = cur->item;
2240 oid = &this->object.oid;
2241 buffer = repo_get_commit_buffer(r, this, &bufsize);
2242 if (!buffer) {
2243 res = error(_("cannot read commit buffer for %s"), oid_to_hex(oid));
2244 goto out;
2245 }
2246
2247 p = strstr(buffer, "\n\n");
2248 if (!p) {
2249 res = error(_("cannot parse commit %s"), oid_to_hex(oid));
2250 goto out;
2251 }
2252
2253 p += 2;
2254 msg = xmemdupz(p, bufsize - (p - buffer));
2255 repo_unuse_commit_buffer(r, this, buffer);
2256 buffer = NULL;
2257
2258 if (do_store_stash(oid, msg, 1)) {
2259 res = error(_("cannot save the stash for %s"), oid_to_hex(oid));
2260 goto out;
2261 }
2262 FREE_AND_NULL(msg);
2263 }
2264 out:
2265 if (this && buffer)
2266 repo_unuse_commit_buffer(r, this, buffer);
2267 commit_list_free(items);
2268 free(msg);
2269
2270 return res;
2271 }
2272
2273 static int import_stash(int argc, const char **argv, const char *prefix,
2274 struct repository *repo)
2275 {
2276 struct option options[] = {
2277 OPT_END()
2278 };
2279
2280 argc = parse_options(argc, argv, prefix, options,
2281 git_stash_import_usage,
2282 PARSE_OPT_KEEP_DASHDASH);
2283
2284 if (argc != 1)
2285 usage_msg_opt("a revision is required", git_stash_import_usage, options);
2286
2287 return do_import_stash(repo, argv[0]);
2288 }
2289
2290 struct stash_entry_data {
2291 struct repository *r;
2292 struct commit_list **items;
2293 size_t count;
2294 };
2295
2296 static int collect_stash_entries(const char *refname UNUSED,
2297 struct object_id *old_oid UNUSED,
2298 struct object_id *new_oid,
2299 const char *committer UNUSED,
2300 timestamp_t timestamp UNUSED,
2301 int tz UNUSED, const char *msg UNUSED,
2302 void *cb_data)
2303 {
2304 struct stash_entry_data *data = cb_data;
2305 struct commit *stash;
2306
2307 data->count++;
2308 stash = lookup_commit_reference(data->r, new_oid);
2309 if (!stash || check_stash_topology(data->r, stash)) {
2310 return error(_("%s does not look like a stash commit"),
2311 oid_to_hex(new_oid));
2312 }
2313 data->items = commit_list_append(stash, data->items);
2314 return 0;
2315 }
2316
2317 static int do_export_stash(struct repository *r,
2318 const char *ref,
2319 int argc,
2320 const char **argv)
2321 {
2322 struct object_id base;
2323 struct commit *prev;
2324 struct commit_list *items = NULL, **iter = &items, *cur;
2325 int res = 0;
2326 int i;
2327 struct strbuf revision = STRBUF_INIT;
2328 const char *author, *committer;
2329
2330 /*
2331 * This is an arbitrary, fixed date, specifically the one used by git
2332 * format-patch. The goal is merely to produce reproducible output.
2333 */
2334 prepare_fallback_ident("git stash", "git@stash");
2335 author = fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT,
2336 "2001-09-17T00:00:00Z", 0);
2337 committer = fmt_ident("git stash", "git@stash", WANT_BLANK_IDENT,
2338 "2001-09-17T00:00:00Z", 0);
2339
2340 /* First, we create a single empty commit. */
2341 if (commit_tree_extended("", 0, r->hash_algo->empty_tree, NULL,
2342 &base, author, committer, NULL, NULL))
2343 return error(_("unable to write base commit"));
2344
2345 prev = lookup_commit_reference(r, &base);
2346
2347 if (argc) {
2348 /*
2349 * Find each specified stash, and load data into the array.
2350 */
2351 for (i = 0; i < argc; i++) {
2352 struct object_id oid;
2353 struct commit *stash;
2354
2355 if (parse_stash_revision(&revision, argv[i], 1) ||
2356 repo_get_oid_with_flags(r, revision.buf, &oid,
2357 GET_OID_QUIETLY |
2358 GET_OID_GENTLY)) {
2359 res = error(_("unable to find stash entry %s"), argv[i]);
2360 goto out;
2361 }
2362
2363 stash = lookup_commit_reference(r, &oid);
2364 if (!stash || check_stash_topology(r, stash)) {
2365 res = error(_("%s does not look like a stash commit"),
2366 revision.buf);
2367 goto out;
2368 }
2369 iter = commit_list_append(stash, iter);
2370 }
2371 } else {
2372 /*
2373 * Walk the reflog, finding each stash entry, and load data into the
2374 * array.
2375 */
2376 struct stash_entry_data cb_data = {
2377 .r = r, .items = iter,
2378 };
2379 if (refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
2380 "refs/stash",
2381 collect_stash_entries,
2382 &cb_data) && cb_data.count)
2383 goto out;
2384 }
2385
2386 /*
2387 * Now, create a set of commits identical to the regular stash commits,
2388 * but where their first parents form a chain to our original empty
2389 * base commit.
2390 */
2391 items = commit_list_reverse(items);
2392 for (cur = items; cur; cur = cur->next) {
2393 struct commit_list *parents = NULL;
2394 struct commit_list **next = &parents;
2395 struct object_id out;
2396 struct commit *stash = cur->item;
2397
2398 next = commit_list_append(prev, next);
2399 next = commit_list_append(stash, next);
2400 res = write_commit_with_parents(r, &out, &stash->object.oid, parents);
2401 commit_list_free(parents);
2402 if (res)
2403 goto out;
2404 prev = lookup_commit_reference(r, &out);
2405 }
2406 if (ref)
2407 refs_update_ref(get_main_ref_store(r), NULL, ref,
2408 &prev->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
2409 else
2410 puts(oid_to_hex(&prev->object.oid));
2411 out:
2412 strbuf_release(&revision);
2413 commit_list_free(items);
2414
2415 return res;
2416 }
2417
2418 enum export_action {
2419 ACTION_NONE,
2420 ACTION_PRINT,
2421 ACTION_TO_REF,
2422 };
2423
2424 static int export_stash(int argc,
2425 const char **argv,
2426 const char *prefix,
2427 struct repository *repo)
2428 {
2429 const char *ref = NULL;
2430 enum export_action action = ACTION_NONE;
2431 struct option options[] = {
2432 OPT_CMDMODE(0, "print", &action,
2433 N_("print the object ID instead of writing it to a ref"),
2434 ACTION_PRINT),
2435 OPT_STRING(0, "to-ref", &ref, "ref",
2436 N_("save the data to the given ref")),
2437 OPT_END()
2438 };
2439
2440 argc = parse_options(argc, argv, prefix, options,
2441 git_stash_export_usage,
2442 PARSE_OPT_KEEP_DASHDASH);
2443
2444 if (ref && action == ACTION_NONE)
2445 action = ACTION_TO_REF;
2446
2447 if (action == ACTION_NONE || (ref && action == ACTION_PRINT))
2448 return error(_("exactly one of --print and --to-ref is required"));
2449
2450 return do_export_stash(repo, ref, argc, argv);
2451 }
2452
2453 int cmd_stash(int argc,
2454 const char **argv,
2455 const char *prefix,
2456 struct repository *repo)
2457 {
2458 pid_t pid = getpid();
2459 const char *index_file;
2460 struct strvec args = STRVEC_INIT;
2461 parse_opt_subcommand_fn *fn = NULL;
2462 struct option options[] = {
2463 OPT_SUBCOMMAND("apply", &fn, apply_stash),
2464 OPT_SUBCOMMAND("clear", &fn, clear_stash),
2465 OPT_SUBCOMMAND("drop", &fn, drop_stash),
2466 OPT_SUBCOMMAND("pop", &fn, pop_stash),
2467 OPT_SUBCOMMAND("branch", &fn, branch_stash),
2468 OPT_SUBCOMMAND("list", &fn, list_stash),
2469 OPT_SUBCOMMAND("show", &fn, show_stash),
2470 OPT_SUBCOMMAND("store", &fn, store_stash),
2471 OPT_SUBCOMMAND("create", &fn, create_stash),
2472 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
2473 OPT_SUBCOMMAND("export", &fn, export_stash),
2474 OPT_SUBCOMMAND("import", &fn, import_stash),
2475 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
2476 OPT_END()
2477 };
2478 const char **args_copy;
2479 int ret;
2480
2481 repo_config(the_repository, git_stash_config, NULL);
2482
2483 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
2484 PARSE_OPT_SUBCOMMAND_OPTIONAL |
2485 PARSE_OPT_KEEP_UNKNOWN_OPT |
2486 PARSE_OPT_KEEP_DASHDASH);
2487
2488 prepare_repo_settings(the_repository);
2489 the_repository->settings.command_requires_full_index = 0;
2490
2491 index_file = repo_get_index_file(the_repository);
2492 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
2493 (uintmax_t)pid);
2494
2495 if (fn)
2496 return !!fn(argc, argv, prefix, repo);
2497 else if (!argc)
2498 return !!push_stash_unassumed(0, NULL, prefix, repo);
2499
2500 /* Assume 'stash push' */
2501 strvec_push(&args, "push");
2502 strvec_pushv(&args, argv);
2503
2504 /*
2505 * `push_stash()` ends up modifying the array, which causes memory
2506 * leaks if we didn't copy the array here.
2507 */
2508 DUP_ARRAY(args_copy, args.v, args.nr);
2509
2510 ret = !!push_stash(args.nr, args_copy, prefix, 1);
2511
2512 strvec_clear(&args);
2513 free(args_copy);
2514 return ret;
2515 }