code.gitea.io/gitea@v1.21.7/build/generate-bindata.go (about)

     1  // Copyright 2020 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  //go:build ignore
     5  
     6  package main
     7  
     8  import (
     9  	"bytes"
    10  	"crypto/sha1"
    11  	"fmt"
    12  	"log"
    13  	"net/http"
    14  	"os"
    15  	"path/filepath"
    16  	"strconv"
    17  
    18  	"github.com/shurcooL/vfsgen"
    19  )
    20  
    21  func needsUpdate(dir, filename string) (bool, []byte) {
    22  	needRegen := false
    23  	_, err := os.Stat(filename)
    24  	if err != nil {
    25  		needRegen = true
    26  	}
    27  
    28  	oldHash, err := os.ReadFile(filename + ".hash")
    29  	if err != nil {
    30  		oldHash = []byte{}
    31  	}
    32  
    33  	hasher := sha1.New()
    34  
    35  	err = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
    36  		if err != nil {
    37  			return err
    38  		}
    39  		info, err := d.Info()
    40  		if err != nil {
    41  			return err
    42  		}
    43  		_, _ = hasher.Write([]byte(d.Name()))
    44  		_, _ = hasher.Write([]byte(info.ModTime().String()))
    45  		_, _ = hasher.Write([]byte(strconv.FormatInt(info.Size(), 16)))
    46  		return nil
    47  	})
    48  	if err != nil {
    49  		return true, oldHash
    50  	}
    51  
    52  	newHash := hasher.Sum([]byte{})
    53  
    54  	if bytes.Compare(oldHash, newHash) != 0 {
    55  		return true, newHash
    56  	}
    57  
    58  	return needRegen, newHash
    59  }
    60  
    61  func main() {
    62  	if len(os.Args) < 4 {
    63  		log.Fatal("Insufficient number of arguments. Need: directory packageName filename")
    64  	}
    65  
    66  	dir, packageName, filename := os.Args[1], os.Args[2], os.Args[3]
    67  	var useGlobalModTime bool
    68  	if len(os.Args) == 5 {
    69  		useGlobalModTime, _ = strconv.ParseBool(os.Args[4])
    70  	}
    71  
    72  	update, newHash := needsUpdate(dir, filename)
    73  
    74  	if !update {
    75  		fmt.Printf("bindata for %s already up-to-date\n", packageName)
    76  		return
    77  	}
    78  
    79  	fmt.Printf("generating bindata for %s\n", packageName)
    80  	var fsTemplates http.FileSystem = http.Dir(dir)
    81  	err := vfsgen.Generate(fsTemplates, vfsgen.Options{
    82  		PackageName:      packageName,
    83  		BuildTags:        "bindata",
    84  		VariableName:     "Assets",
    85  		Filename:         filename,
    86  		UseGlobalModTime: useGlobalModTime,
    87  	})
    88  	if err != nil {
    89  		log.Fatalf("%v\n", err)
    90  	}
    91  	_ = os.WriteFile(filename+".hash", newHash, 0o666)
    92  }