cmd/golangorg: add -a flag to automatically find templates

We'd like to make it possible for people to run the web site with

	go run ./cmd/golangorg -a

without having to worry about go generate or figuring out the -templates flag.
This is a step in that direction: it sets -templates correctly.

Even so, -templates is still incompatible with Markdown files.

Change-Id: I97afaafdbc66500c674c959383334bf2e5185316
Reviewed-on: https://go-review.googlesource.com/c/website/+/251377
Trust: Russ Cox <rsc@golang.org>
Trust: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
diff --git a/cmd/golangorg/main.go b/cmd/golangorg/main.go
index 55fae19..c805c02 100644
--- a/cmd/golangorg/main.go
+++ b/cmd/golangorg/main.go
@@ -64,6 +64,7 @@
 	goroot = flag.String("goroot", findGOROOT(), "Go root directory")
 
 	// layout control
+	autoFlag       = flag.Bool("a", false, "update templates automatically")
 	showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings")
 	templateDir    = flag.String("templates", "", "load templates/JS/CSS from disk in this directory (usually /path-to-website/content/static)")
 	showPlayground = flag.Bool("play", false, "enable playground")
@@ -112,6 +113,26 @@
 	flag.Usage = usage
 	flag.Parse()
 
+	// Find templates in -a mode.
+	if *autoFlag {
+		if *templateDir != "" {
+			fmt.Fprintln(os.Stderr, "Cannot use -a and -templates together.")
+			usage()
+		}
+		_, file, _, ok := runtime.Caller(0)
+		if !ok {
+			fmt.Fprintln(os.Stderr, "runtime.Caller failed: cannot find templates for -a mode.")
+			os.Exit(2)
+		}
+		dir := filepath.Join(file, "../../../content/static")
+		if _, err := os.Stat(filepath.Join(dir, "godoc.html")); err != nil {
+			fmt.Fprintln(os.Stderr, err)
+			fmt.Fprintln(os.Stderr, "Cannot find templates for -a mode.")
+			os.Exit(2)
+		}
+		*templateDir = dir
+	}
+
 	playEnabled = *showPlayground
 
 	// Check usage.