# Copyright 2012 The Go Authors.  All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# These function names are also known to
# (and are the plan for transitioning to) run.go.

# helper (not known to run.go)
# group file list by packages and return list of packages
# each package is a comma-separated list of go files.
pkgs() {
	pkglist=$(grep -h '^package ' $* | awk '{print $2}' | sort -u)
	for p in $pkglist
	do
		echo $(grep -l "^package $p\$" $*) | tr ' ' ,
	done | sort
}

# +build aborts execution if the supplied tags don't match,
# i.e. none of the tags (x or !x) matches GOARCH or GOOS.
+build() {
	if (( $# == 0 )); then
		return
	fi
	for tag; do
		case $tag in
		$GOARCH|$GOOS)
			#echo >&2 "match $tag in $1"
			return # don't exclude.
			;;
		'!'$GOARCH|'!'$GOOS)
			;;
		'!'*)
			# not x where x is neither GOOS nor GOARCH.
			#echo >&2 "match $tag in $1"
			return # don't exclude
			;;
		esac
	done
	# no match.
	exit 0
}

compile() {
	$G $D/$F.go
}

compiledir() {
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		$G -I . $(echo $pkg | tr , ' ') || return 1
	done
}

errorcheckdir() {
	lastzero=""
	if [ "$1" = "-0" ]; then
		lastzero="-0"
	fi
	pkgs=$(pkgs $D/$F.dir/*.go)
	for pkg in $pkgs.last
	do
		zero="-0"
		case $pkg in
		*.last)
			pkg=$(echo $pkg |sed 's/\.last$//')
			zero=$lastzero
		esac
		errchk $zero $G -D . -I . -e $(echo $pkg | tr , ' ')
	done
}

rundir() {
	lastfile=""
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		name=$(echo $pkg | sed 's/\.go.*//; s/.*\///')
		$G -D . -I . -e $(echo $pkg | tr , ' ') || return 1
		lastfile=$name
	done
	$L -o $A.out -L . $lastfile.$A
	./$A.out
}

rundircmpout() {
	lastfile=""
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		name=$(echo $pkg | sed 's/\.go.*//; s/.*\///')
		$G -D . -I . -e $(echo $pkg | tr , ' ') || return 1
		lastfile=$name
	done
	$L -o $A.out -L . $lastfile.$A
	./$A.out 2>&1 | cmp - $D/$F.out
}

build() {
	$G $D/$F.go && $L $F.$A
}

runoutput() {
	go run "$D/$F.go" "$@" > tmp.go
	go run tmp.go
}

run() {
	gofiles=""
	ingo=true
	while $ingo; do
		case "$1" in
		*.go)
			gofiles="$gofiles $1"
			shift
			;;
		*)
			ingo=false
			;;
		esac
	done

	$G $D/$F.go $gofiles && $L $F.$A && ./$A.out "$@"
}

cmpout() {
	$G $D/$F.go && $L $F.$A && ./$A.out 2>&1 | cmp - $D/$F.out
}

errorcheck() {
	zero=""
	if [ "$1" = "-0" ]; then
		zero="-0"
		shift
	fi
	errchk $zero $G -e $* $D/$F.go
}

errorcheckoutput() {
	zero=""
	if [ "$1" = "-0" ]; then
		zero="-0"
		shift
	fi
	go run "$D/$F.go" "$@" > tmp.go
	errchk $zero $G -e tmp.go
}

skip() {
	true
}
