blob: 24b0685839ebd068fb52cad04e432f0bb25af767 [file] [log] [blame]
David K. Bainbridge215e0242017-09-05 23:18:24 -07001// Copyright 2016 Claudemiro Alves Feitosa Neto. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package banner
6
7import (
8 "io"
9 "io/ioutil"
10 "log"
11 "os"
12 "runtime"
13 "text/template"
14 "time"
15)
16
17var logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
18
19// SetLog permits the user change the default logger instance
20func SetLog(l *log.Logger) {
21 if l == nil {
22 return
23 }
24 logger = l
25}
26
27type vars struct {
28 GoVersion string
29 GOOS string
30 GOARCH string
31 NumCPU int
32 GOPATH string
33 GOROOT string
34 Compiler string
35 AnsiColor ansiColor
36 AnsiBackground ansiBackground
37}
38
39func (v vars) Env(env string) string {
40 return os.Getenv(env)
41}
42
43// See https://github.com/golang/go/blob/f06795d9b742cf3292a0f254646c23603fc6419b/src/time/format.go#L9-L41
44func (v vars) Now(layout string) string {
45 return time.Now().Format(layout)
46}
47
48// Init load the banner and prints it to output
49// All errors are ignored, the application will not print the banner in case of error.
50func Init(out io.Writer, isEnabled, isColorEnabled bool, in io.Reader) {
51 if !isEnabled {
52 logger.Println("The banner is not enabled.")
53 return
54 }
55
56 if in == nil {
57 logger.Println("The input is nil")
58 return
59 }
60
61 banner, err := ioutil.ReadAll(in)
62
63 if err != nil {
64 logger.Printf("Error trying to read the banner, err: %v", err)
65 return
66 }
67
68 show(out, isColorEnabled, string(banner))
69}
70
71func show(out io.Writer, isColorEnabled bool, content string) {
72 t, err := template.New("banner").Parse(content)
73
74 if err != nil {
75 logger.Printf("Error trying to parse the banner file, err: %v", err)
76 return
77 }
78
79 t.Execute(out, vars{
80 runtime.Version(),
81 runtime.GOOS,
82 runtime.GOARCH,
83 runtime.NumCPU(),
84 os.Getenv("GOPATH"),
85 runtime.GOROOT(),
86 runtime.Compiler,
87 ansiColor{isColorEnabled},
88 ansiBackground{isColorEnabled},
89 })
90}