#!/usr/bin/env bash
#
# Pull and merge changes from a branch to the local repository.
# Copyright (c) Petr Baudis, 2005
#
# Takes the branch name as an argument, defaulting to 'origin'.
#
# This is basically equivalent to running cg-fetch and cg-merge commands
# successively. Please refer to the documentation of those commands for
# more details about the operation.
#
# Note that in the GIT newspeak, the operation being performed by cg-update
# is now called 'pull', even though in the past, 'pull' was the name for
# the operation being now done by cg-fetch, which is even still aliased
# to cg-pull. Please do not let this confuse you. (Cogito won't call this
# 'update' operation 'pull', since about everyone but GIT and BK users uses
# it in the 'fetch' meaning.)
#
# OPTIONS
# -------
# -f::
#	Force the complete fetch even if the heads are the same.
#
# --squash::
#	"Squash" merge - condense all the to-be-merged commits to a single
#	merge commit. This is not to be used lightly; see the cg-merge
#	documenation for further details.

USAGE="cg-update [-f] [--squash] [BRANCH_NAME]"
_git_requires_root=1

. ${COGITO_LIB}cg-Xlib || exit 1

force=
squash=
while optparse; do
	if optparse -f; then
		force=-f
	elif optparse --squash; then
		squash=--squash
	else
		optfail
	fi
done

name=${ARGS[0]}
[ "$name" ] || { [ -s $_git/branches/origin ] && name=origin; }
[ "$name" ] || die "where to update from?"

if [ -s "$_git/branches/$name" ]; then
	cg-fetch $force $name || exit 1
else
	echo "Updating from a local branch."
fi
echo
echo "Applying changes..."
cg-merge $squash $name
