#!/usr/bin/env bash
#
# Cancels current edits in the working tree.
# Copyright (c) Petr Baudis, 2005
#
# Reverts the working tree to a consistent state before any changes to it
# (including merges etc.) were done.
#
# Basically, this is the opposite of `cg-commit` in some sense.
#
# This command is complementary to `cg-restore`, which only brings
# individual files in sync with their state at the time of the
# last commit.

USAGE="cg-cancel"

. ${COGITO_LIB}cg-Xlib

if ! [ -s $_git/HEAD ]; then
	rm -f $_git/HEAD
	ln -s refs/heads/master $_git/HEAD
fi

# Undo seek?
branch=
[ -s $_git/blocked ] && branch=$(grep '^seeked from ' $_git/blocked | sed 's/^seeked from //')
if [ "$branch" ]; then
	echo "Unseeking: $(cat $_git/HEAD) -> $(cat "$_git/refs/heads/$branch")"
	if [ -s "$_git/refs/heads/$branch" ]; then
		rm $_git/HEAD
		ln -s "refs/heads/$branch" $_git/HEAD
	else
		echo "ERROR: Unknown branch $branch! Preserving HEAD." >&2
	fi
fi

rm -f $_git/blocked $_git/merging $_git/merging-sym $_git/merge-base
git-read-tree -m HEAD || git-read-tree HEAD

git-checkout-cache -f -a
git-update-cache --refresh
