Sometimes I need a quick scratch area to test out an idea, so I wrote this script.

  • optionally deletes the folder after you’re done.
  • helper for go2 if you have it installed.

source

#!/bin/bash
set -e
export GO111MODULE=auto
EDITOR="code --new-window --wait"
GOPATH="$(go env GOPATH)"
BASE="$GOPATH/src/tmp/"

ARG=${1:-go}

if [ $ARG = "-d" ]; then
	echo -n "delete '$BASE'? " && read Y
	[ "$Y" = "y" ] && rm -vrf "$BASE"
	exit 0
fi

if [ "$ARG" != "go" -a "$ARG" != "go2" -a "$ARG" != "-d" ]; then
	echo "usage: $0 [go|go2] -d (delete all tmp folders)" > /dev/stderr
	exit 1
fi

mkdir -p "$BASE"
D="$(mktemp -d -p "$BASE" go-scratch.XXX)"
mkdir -p "$D/.vscode"
if [ $ARG = "go2" ]; then
	echo '{"version":"2.0.0","tasks":[{"label":"go2go","type":"shell","command":"go tool go2go translate ${fileBasename}","problemMatcher":"$go","presentation":{"reveal":"silent","clear":true}}]}' > "$D/.vscode/tasks.json"
	echo '{"version":"0.2.0","configurations":[{"name":"Launch","type":"go","request":"launch","mode":"auto","program":"${fileDirname}","preLaunchTask":"go2go"}]}' > "$D/.vscode/launch.json"
else
	echo '{"version":"0.2.0","configurations":[{"name":"Launch","type":"go","request":"launch","mode":"auto","program":"${fileDirname}"}]}' > "$D/.vscode/launch.json"
fi

echo "package main

import (
	\"log\"
)

func main() {
	pf(\"hello %s\", \"world\")
}

func init() {
	log.SetFlags(log.Lshortfile)
}

var (
	pln = log.Println
	pf = log.Printf
)

func dieIf(err error) {
	if err != nil {
		log.Output(2, err.Error())
		panic(err.Error())
	}
}
" > "${D}/main.$ARG"

echo "package main

import (
	\"testing\"
)

func TestMain(t *testing.T) {
	t.Log(\".\")
}

func BenchmarkMain(b *testing.B) {
	b.ReportAllocs()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			//
		}
	})
}" > "${D}/main_test.$ARG"

$EDITOR "$D" "$D/main.$ARG"

echo -n "delete '$D'? " && read Y
[ "$Y" = "y" ] && rm -vrf "$D"