summaryrefslogtreecommitdiffstats
path: root/build/generate-bindata.go
blob: fa1669fcf9fb149b4e0e4194b97169e15b872cc4 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import (
	"bytes"
	"crypto/sha1"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"github.com/shurcooL/vfsgen"
)

func needsUpdate(dir string, filename string) (bool, []byte) {
	needRegen := false
	_, err := os.Stat(filename)
	if err != nil {
		needRegen = true
	}

	oldHash, err := ioutil.ReadFile(filename + ".hash")
	if err != nil {
		oldHash = []byte{}
	}

	hasher := sha1.New()

	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		_, _ = hasher.Write([]byte(info.Name()))
		_, _ = hasher.Write([]byte(info.ModTime().String()))
		_, _ = hasher.Write([]byte(strconv.FormatInt(info.Size(), 16)))
		return nil
	})
	if err != nil {
		return true, oldHash
	}

	newHash := hasher.Sum([]byte{})

	if bytes.Compare(oldHash, newHash) != 0 {

		return true, newHash
	}

	return needRegen, newHash
}

func main() {
	if len(os.Args) != 4 {
		log.Fatal("Insufficient number of arguments. Need: directory packageName filename")
	}

	dir, packageName, filename := os.Args[1], os.Args[2], os.Args[3]

	update, newHash := needsUpdate(dir, filename)

	if !update {
		fmt.Printf("bindata for %s already up-to-date\n", packageName)
		return
	}

	fmt.Printf("generating bindata for %s\n", packageName)
	var fsTemplates http.FileSystem = http.Dir(dir)
	err := vfsgen.Generate(fsTemplates, vfsgen.Options{
		PackageName:  packageName,
		BuildTags:    "bindata",
		VariableName: "Assets",
		Filename:     filename,
	})
	if err != nil {
		log.Fatalf("%v\n", err)
	}
	_ = ioutil.WriteFile(filename+".hash", newHash, 0666)
}