interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / stash.c

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