stash: simplify reflog emptiness check

Calling rev-parse to check if the drop subcommand removed the last stash and treating its failure as confirmation is fragile, as the command can fail for other reasons, e.g. because the system is out of memory. Directly check if the reflog is empty instead, which is more robust. Reported-by: Marek Mrva <mrva@eof-studios.com> Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Oct 24, 2020 at 19:06 UTC 4f44c5659bfb6e80fe76e68ec775859915d5f94a
1 file changed +13 -14
builtin/stash.c
+13 -14
@@ -534,11 +534,22 @@ static int apply_stash(int argc, const char **argv, const char *prefix)
534 return ret;
535 }
536
537 +static int reject_reflog_ent(struct object_id *ooid, struct object_id *noid,
538 + const char *email, timestamp_t timestamp, int tz,
539 + const char *message, void *cb_data)
540 +{
541 + return 1;
542 +}
543 +
544 +static int reflog_is_empty(const char *refname)
545 +{
546 + return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
547 +}
548 +
549 static int do_drop_stash(struct stash_info *info, int quiet)
550 {
551 int ret;
552 struct child_process cp_reflog = CHILD_PROCESS_INIT;
541 - struct child_process cp = CHILD_PROCESS_INIT;
553
554 /*
555 * reflog does not provide a simple function for deleting refs. One will
@@ -559,19 +570,7 @@ static int do_drop_stash(struct stash_info *info, int quiet)
570 info->revision.buf);
571 }
572
562 - /*
563 - * This could easily be replaced by get_oid, but currently it will throw
564 - * a fatal error when a reflog is empty, which we can not recover from.
565 - */
566 - cp.git_cmd = 1;
567 - /* Even though --quiet is specified, rev-parse still outputs the hash */
568 - cp.no_stdout = 1;
569 - strvec_pushl(&cp.args, "rev-parse", "--verify", "--quiet", NULL);
570 - strvec_pushf(&cp.args, "%s@{0}", ref_stash);
571 - ret = run_command(&cp);
572 -
573 - /* do_clear_stash if we just dropped the last stash entry */
574 - if (ret)
573 + if (reflog_is_empty(ref_stash))
574 do_clear_stash();
575
576 return 0;