go-hep.org/x/hep@v0.38.1/groot/internal/genroot/genroot.go (about)

     1  // Copyright ©2018 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package genroot // import "go-hep.org/x/hep/groot/internal/genroot"
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/format"
    11  	"io"
    12  	"log"
    13  	"os"
    14  	"strconv"
    15  	"time"
    16  )
    17  
    18  // GoFmt formats a file using gofmt.
    19  func GoFmt(f *os.File) {
    20  	fname := f.Name()
    21  	src, err := os.ReadFile(fname)
    22  	if err != nil {
    23  		log.Fatal(err)
    24  	}
    25  	src, err = format.Source(src)
    26  	if err != nil {
    27  		log.Fatalf("error formating sources of %q: %v\n", fname, err)
    28  	}
    29  
    30  	err = os.WriteFile(fname, src, 0644)
    31  	if err != nil {
    32  		log.Fatalf("error writing back %q: %v\n", fname, err)
    33  	}
    34  }
    35  
    36  // GenImports adds the provided imports to the given writer.
    37  func GenImports(year int, pkg string, w io.Writer, imports ...string) {
    38  	if year <= 0 {
    39  		year = gopherYear
    40  	}
    41  	fmt.Fprintf(w, srcHeader, year, pkg)
    42  	if len(imports) == 0 {
    43  		return
    44  	}
    45  
    46  	fmt.Fprintf(w, "import (\n")
    47  	for _, imp := range imports {
    48  		if imp == "" {
    49  			fmt.Fprintf(w, "\n")
    50  			continue
    51  		}
    52  		fmt.Fprintf(w, "\t%q\n", imp)
    53  	}
    54  	fmt.Fprintf(w, ")\n\n")
    55  }
    56  
    57  // ExtractYear returns the copyright year of a Go-HEP header file.
    58  func ExtractYear(fname string) int {
    59  	raw, err := os.ReadFile(fname)
    60  	if err != nil {
    61  		return gopherYear
    62  	}
    63  	if !bytes.HasPrefix(raw, []byte("// Copyright")) {
    64  		return gopherYear
    65  	}
    66  	raw = bytes.TrimPrefix(raw, []byte("// Copyright ©"))
    67  	raw = bytes.TrimPrefix(raw, []byte("// Copyright "))
    68  	idx := bytes.Index(raw, []byte("The go-hep Authors"))
    69  	raw = bytes.TrimSpace(raw[:idx])
    70  
    71  	year, err := strconv.Atoi(string(raw))
    72  	if err != nil {
    73  		return gopherYear
    74  	}
    75  	return year
    76  }
    77  
    78  var gopherYear = time.Now().Year()
    79  
    80  const srcHeader = `// Copyright ©%d The go-hep Authors. All rights reserved.
    81  // Use of this source code is governed by a BSD-style
    82  // license that can be found in the LICENSE file.
    83  
    84  // Automatically generated. DO NOT EDIT.
    85  
    86  package %s
    87  
    88  `