aboutsummaryrefslogtreecommitdiff
path: root/write.go
blob: 703b3864b255f180ad41ffc7c828cd44c9a11a70 (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main

import (
	"bytes"
	"fmt"
	"html/template"
	"io/ioutil"
	"os"
	"path/filepath"
)

const (
	indexTplPath    = "templates/index.tpl"
	packagesTplPath = "templates/package.tpl"
)

// Write takes a Config and produces a static html site to outDir
func Write(c Config, outDir string) error {
	if err := os.MkdirAll(outDir, 0755); err != nil {
		return err
	}
	if err := writeIndex(c, outDir); err != nil {
		return err
	}
	if err := writePackages(c, outDir); err != nil {
		return err
	}
	return nil
}

func writeIndex(c Config, outDir string) error {
	tpl, err := Asset(indexTplPath)
	if err != nil {
		return err
	}

	t, err := template.New(filepath.Base(indexTplPath)).Parse(string(tpl))
	if err != nil {
		return err
	}

	buf := new(bytes.Buffer)
	if err := t.Execute(buf, c); err != nil {
		return err
	}

	err = ioutil.WriteFile(fmt.Sprintf("%s/index.html", outDir), buf.Bytes(), 0644)
	if err != nil {
		return err
	}

	fmt.Println(buf.String())
	return nil
}

func writePackages(c Config, outDir string) error {
	tpl, err := Asset(packagesTplPath)
	if err != nil {
		return err
	}

	t, err := template.New(filepath.Base(packagesTplPath)).Parse(string(tpl))
	if err != nil {
		return err
	}

	for name, pkg := range c.Packages {
		canonicalURL := fmt.Sprintf("%s/%s", c.URL, name)
		tpl := struct {
			Name         string
			CanonicalURL string
			GodocURL     string
			Package
		}{
			Name:         name,
			CanonicalURL: canonicalURL,
			GodocURL:     fmt.Sprintf("https://godoc.org/%s", canonicalURL),
			Package:      pkg,
		}

		buf := new(bytes.Buffer)
		if err := t.Execute(buf, tpl); err != nil {
			return err
		}

		if err := ioutil.WriteFile(fmt.Sprintf("%s/%s.html", outDir, name), buf.Bytes(), 0644); err != nil {
			return err
		}

		fmt.Println(buf)
	}

	return nil
}