summaryrefslogtreecommitdiffstats
path: root/src/cmd/go/internal/vcweb/fossil.go
blob: 4b5db22b0aad33de3321219e4975befac8c708b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2017 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.

package vcweb

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/cgi"
	"os"
	"os/exec"
	"path/filepath"
	"sync"
)

type fossilHandler struct {
	once          sync.Once
	fossilPath    string
	fossilPathErr error
}

func (h *fossilHandler) Available() bool {
	h.once.Do(func() {
		h.fossilPath, h.fossilPathErr = exec.LookPath("fossil")
	})
	return h.fossilPathErr == nil
}

func (h *fossilHandler) Handler(dir string, env []string, logger *log.Logger) (http.Handler, error) {
	if !h.Available() {
		return nil, ServerNotInstalledError{name: "fossil"}
	}

	name := filepath.Base(dir)
	db := filepath.Join(dir, name+".fossil")

	cgiPath := db + ".cgi"
	cgiScript := fmt.Sprintf("#!%s\nrepository: %s\n", h.fossilPath, db)
	if err := ioutil.WriteFile(cgiPath, []byte(cgiScript), 0755); err != nil {
		return nil, err
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if _, err := os.Stat(db); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		ch := &cgi.Handler{
			Env:    env,
			Logger: logger,
			Path:   h.fossilPath,
			Args:   []string{cgiPath},
			Dir:    dir,
		}
		ch.ServeHTTP(w, req)
	})

	return handler, nil
}